Android:OnResume导致强制关闭

时间:2011-09-15 19:50:50

标签: android onresume

我正在尝试创建一个简单的记事本应用程序,并且我想在New Note活动完成并且主屏幕恢复时刷新笔记。但是,当我尝试使用此代码打开应用程序时,我会强行关闭。如果我删除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);
}
}

1 个答案:

答案 0 :(得分:4)

问题是您有两个不同的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(...)中,您尝试使用null的实例成员tw ...

protected void onResume() {
    ...
    tw.setText(data);

onCreate中的行更改为...

tw = (TextView)findViewById(R.id.uusi);

......它应该解决问题。

顺便说一句,您不需要在onCreate(...)中再次复制onResume()中的所有内容,因为在创建活动时onResume()之后始终会调用onCreate(...)