gpt4 book ai didi

java - 使用我的第一个 HelloWorldLogin android 代码获取 "Force Close"

转载 作者:行者123 更新时间:2023-12-01 15:21:13 24 4
gpt4 key购买 nike

我试图通过这里的实验室https://sites.google.com/site/androidcoursearchive/labs/lab-1来学习

这是代码

NameGetter.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: Unable to start activity ComponentInfo{com.mypackagerhello.com/com.mypackagerhello.com.HelloWorld}: java.lang.NullPointerException`

编辑:谢谢大家! HelloWorld.java 中缺少 this.setContentView(R.layout.main); 行。

最佳答案

请注意,在您的 NameGetter Activity 中,您设置内容 View 如下:

this.setContentView(R.layout.name_getter);

但在您的 HelloWorld Activity 中您还没有这样做。将该行添加到 super.onCreate 之后和 findViewById 之前。祝你好运!

关于java - 使用我的第一个 HelloWorldLogin android 代码获取 "Force Close",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10892923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com