dude
dude

Reputation: 41

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

Upvotes: 1

Views: 670

Answers (1)

Squonk
Squonk

Reputation: 48871

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.

Upvotes: 4

Related Questions