1

我正在尝试制作一个简单的记事本应用程序,并且我想在 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);
}
}
4

1 回答 1

4

问题是您有两个不同TextView的 s 调用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为空的实例成员...

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

将行更改onCreate为...

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

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

顺便说一句,您不需要像在创建 Activity后总是调用的那样onCreate(...)再次复制所有内容。onResume()onResume()onCreate(...)

于 2011-09-15T20:07:19.490 回答