我正在尝试制作一个简单的记事本应用程序,我想在“新笔记”活动完成且主屏幕恢复时刷新笔记。但是,当尝试使用此代码打开应用程序时,我被强制关闭。如果删除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);
...它应该可以解决问题。
顺便说一句,您无需在
onCreate(...)
中再次复制onResume()
中的所有内容,因为创建活动时总是在onResume()
之后调用onCreate(...)
。关于android - Android:OnResume导致强制关闭,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7436686/