开发者

Android: OnResume causes force close

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();开发者_StackOverflow社区
       Note note = new Note(this);
        note.open();
        data = note.getData();
        note.close();
        tw.setText(data);
}
}


The problem is you have two different TextViews called tw see my comments on your code...

public class NotePadActivity extends Activity implements View.OnClickListener {

TextView tw; // This never gets instantiated
...

Another here...

public void onCreate(Bundle savedInstanceState) {
    ...
    // This is instantiated but is local to onCreate(...)
    TextView tw = (TextView)findViewById(R.id.uusi);

Then in onResume(...) you attempt to use the instance member tw which is null...

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

Change the line in onCreate to...

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

...and it should fix the problem.

BTW, you don't need to duplicate everything in onCreate(...) again in onResume() as onResume() is always called after onCreate(...) when an Activity is created.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜