【问题标题】:How to save an android string to text file and then set to textview?如何将android字符串保存到文本文件然后设置为textview?
【发布时间】:2011-12-19 15:06:56
【问题描述】:

我试图在 onPause 方法中将字符串保存到 txt 文件,然后将保存的字符串设置为 textview,但我遇到了问题。我不需要在 onResume 方法中设置字符串。主要问题是让 IO 在 Android 中工作,谢谢。

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();
    }
}

【问题讨论】:

    标签: android io android-file


    【解决方案1】:

    如果您想让变量在会话中保持不变,您最好使用SharedPreference,而不是将其存储到文本文件中。

    【讨论】:

    • 完全正确。如果您经常跨会话使用变量,sharedpreference 是最佳选择。
    猜你喜欢
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 2015-12-05
    相关资源
    最近更新 更多