Android 应用在执行时强制关闭

Android app force close when executed

以下代码的执行崩溃。 没有错误消息。

它应该在按下按钮时打开 Web.java 并创建一个键值。

MainActivity.java

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;

public class MainActivity extends Activity {

    private Button btnGo;
    final Spinner page = (Spinner)findViewById(R.id.txtPage);
    String pageChoice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final SharedPreferences sharedPref =PreferenceManager.getDefaultSharedPreferences(this);
        btnGo = (Button)findViewById(R.id.btnGo);
        btnGo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                pageChoice = page.getSelectedItem().toString();

                //Hopefully will allow for "global" url setting.
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("key1", pageChoice);
                editor.commit();
                startActivity(new Intent(MainActivity.this, Web.class));
            }
        });
    }
}

final Spinner page = (Spinner)findViewById(R.id.txtPage); 放在 setContentView(R.layout.activity_main); 语句之后

findViewById (int id)

Look for a child view with the given id. If this view has the given id, return this view. So While class load it looks for Spinner with txtPage id but it isn’t there. so you are getting null value. Which you are trying to access in onClick Method result is NPE.

这不应该在 class 变量中:

final Spinner page = (Spinner)findViewById(R.id.txtPage);

这需要在 onCreate() 方法中。 setContentView()后,作为方法变量。

findViewById()使用context查找View,这需要有context(并且布局资源需要inflate)。您只能在 onCreate 执行时获取上下文,而不是在加载 class 时获取上下文。