如何获得实例化错误以及如何解决它? [Android]产品

时间:2015-10-04 08:03:47

标签: java android android-activity

我一直在编写一个简单的Android Java程序,到目前为止,我在ImageView中添加了EditText,按钮和activity_main.xml。但是,当我运行它时,使用此MainActivity java类:

public class MainActivity extends Activity {

private Button start = (Button) findViewById(R.id.start);
private EditText nameField = (EditText) findViewById(R.id.nameField);

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    start.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String name = nameField.getText().toString();

        }
    });

}

无效,它返回一个我无法解决的致命错误。它说:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo, java.lang.NullPointerException

我该如何解决?非常感谢!

1 个答案:

答案 0 :(得分:1)

您应该将这些初始化移至onCreate

private Button start = (Button) findViewById(R.id.start);
private EditText nameField = (EditText) findViewById(R.id.nameField);

即:

private Button start;
private EditText nameField;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    start = (Button) findViewById(R.id.start);
    nameField = (EditText) findViewById(R.id.nameField);

    start.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String name = nameField.getText().toString();

        }
    });
}

当您在成员初始化表达式中调用findViewById(R.id.start)时,Activity实例尚未初始化,这会导致NullPointerException