Android:OnResume 导致强制关闭

标签 android onresume

我正在尝试制作一个简单的记事本应用程序,我想在“新建笔记” 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/

相关文章:

android - 在Android中获取文件权限(root)

Android - 从其他应用程序恢复 Activity

android - 传递结果失败 ResultInfo | java.lang.IllegalStateException : Can not perform this action after onSaveInstanceState 错误

android - 离线安装安卓很难[过时]

android - 在模拟器上运行我的 Android 应用程序时遇到错误

Android:在 Activity 恢复中更新 SharedPrefereces 不起作用

android - 如何从 MainActivity 暂停/恢复 SurfaceView?

android 数据库已经关闭 onResume

android - 从 Firebase 获取特定用户的分数和类别

android - 如何将视频转换为base64数据