0

onPause メソッドで文字列を txt ファイルに保存し、後で保存した文字列をテキストビューに設定しようとしていますが、問題が発生しています。onResume メソッドで文字列を設定する必要はありません。主な問題は、Android で IO を動作させることです。ありがとうございます。

String fileNameString="savedString.txt";
String textToSave = "PLEASE SAVE ME";
EditText editText;    

public void onResume() {
    super.onResume();
    TextView textViewString = (TextView)findViewById(R.id.item);
    try {
        InputStream in = openFileInput(fileNameString);
        if (in!=null) {
            InputStreamReader tmp = new InputStreamReader(in);
            BufferedReader reader=new BufferedReader(tmp);
            String str;
            StringBuffer buf=new StringBuffer();

            while ((str=reader.readLine()) != null) {
                buf.append(str+"\n");
            }
            textViewString.setText(str);
            in.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
    }
    catch (Throwable t) {
        Toast
            .makeText(this,"Exception: "+t.toString(),2000)
            .show();
    }
}
public void onPause() {
    super.onPause();
    try {
        OutputStreamWriter out = new OutputStreamWriter(openFileOutput(fileNameString,0));
        out.write(textToSave);
        out.close();
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: " +t.toString(), 2000)
            .show();
    }
}
4

1 に答える 1

3

セッション間で変数を永続化する場合は、変数をテキスト ファイルに格納する代わりに、SharedPreferenceを使用することをお勧めします。

于 2011-11-01T16:06:12.460 に答える