我试图通过以下实验室来学习https://sites.google.com/site/androidcoursearchive/labs/lab-1
这是代码
名称Getter.java
public class NameGetter extends Activity implements OnClickListener {
EditText name;
Button submit;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.name_getter);
name = (EditText) this.findViewById(R.id.editText1);
submit = (Button) this.findViewById(R.id.button1);
submit.setOnClickListener(this);
}
public void onClick(View v) {
String userName = name.getText().toString();
Intent submitIntent = new Intent(NameGetter.this, HelloWorld.class);
submitIntent.putExtra("username", userName);
this.startActivity(submitIntent);
}
}
HelloWorld.java
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = (TextView) this.findViewById(R.id.textViewHello);
Bundle name = this.getIntent().getExtras();
if(name != null) {
String nameEntered = name.getString("username");
if(nameEntered != null) {
tv.setText(nameEntered);
} else {
tv.setText("nameEntered is null");
}
} else {
tv.setText("name is null");
}
}
}
我可以在 EditText 框中输入文本,当我按下提交按钮时,我会强制关闭。LogCat 说如下:
java.lang.RuntimeException:无法启动活动 ComponentInfo{com.mypackagerhello.com/com.mypackagerhello.com.HelloWorld}:java.lang.NullPointerException`
编辑:谢谢大家!这是this.setContentView(R.layout.main);
HelloWorld.java 中缺少的行。