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という2つの異なるものがあることです...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);

次に、 nullでonResume(...)あるインスタンスメンバーを使用しようとしtwます...

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

行をに変更onCreateします...

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

...そしてそれは問題を解決するはずです。

ところで、アクティビティが作成されたときに常に呼び出されるようonCreate(...)に、すべてを再度複製する必要はありません。onResume()onResume()onCreate(...)

于 2011-09-15T20:07:19.490 に答える