我正在尝试制作一个简单的记事本应用程序,我想在“新建笔记” Activity 完成且主屏幕恢复时刷新笔记。但是,当我尝试使用此代码打开应用程序时,我会强制关闭。如果我删除 OnResume 东西,它不会强制关闭。帮忙?
public class NotePadActivity extends Activity implements View.OnClickListener {
TextView tw;
String data;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tw = (TextView)findViewById(R.id.uusi);
tw.setOnClickListener(this);
Note note = new Note(this);
note.open();
data = note.getData();
note.close();
tw.setText(data);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.uusi:
try {
startActivity(new Intent(PadsterActivity.this, Class.forName("com.test.notepad.NewNote")));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Note note = new Note(this);
note.open();
data = note.getData();
note.close();
tw.setText(data);
}
}
最佳答案
问题是你有两个不同的 TextView
叫做 tw
请看我对你代码的评论...
public class NotePadActivity extends Activity implements View.OnClickListener {
TextView tw; // This never gets instantiated
...
这里还有一个...
public void onCreate(Bundle savedInstanceState) {
...
// This is instantiated but is local to onCreate(...)
TextView tw = (TextView)findViewById(R.id.uusi);
然后在 onResume(...)
中,您尝试使用实例成员 tw
,它是 null...
protected void onResume() {
...
tw.setText(data);
将 onCreate
中的行更改为...
tw = (TextView)findViewById(R.id.uusi);
...它应该可以解决问题。
顺便说一句,您不需要在 onResume()
中再次将 onCreate(...)
中的所有内容复制为 onResume()
创建 Activity 时总是在 onCreate(...)
之后调用。
关于Android:OnResume 导致强制关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7436686/