Android:OnResume 导致强制关闭
我正在尝试制作一个简单的记事本应用程序,我想在“新建笔记”活动完成并且主屏幕恢复时刷新笔记。但是,当尝试使用此代码打开应用程序时,我会强制关闭。如果我删除 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);
}
}
I'm trying to make a simple notepad application and I would like to refresh the notes when the New Note activity finishes and the main screen resumes. However I get force close when trying to open the application with this code. If I remove the OnResume thing it doesn't force close. Help?
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是你有两个不同的
TextView
称为tw
请参阅我对你的代码的评论...另一个在这里...
然后在
onResume(...)
您尝试使用为 null 的实例成员tw
...将
onCreate
中的行更改为......它应该可以解决问题。
顺便说一句,您不需要在
onResume()
中再次复制onCreate(...)
中的所有内容,因为onResume()
始终被调用创建 Activity 时的onCreate(...)
之后。The problem is you have two different
TextView
s calledtw
see my comments on your code...Another here...
Then in
onResume(...)
you attempt to use the instance membertw
which is null...Change the line in
onCreate
to......and it should fix the problem.
BTW, you don't need to duplicate everything in
onCreate(...)
again inonResume()
asonResume()
is always called afteronCreate(...)
when an Activity is created.