Tom
Tom

Reputation: 1

How to save an android string to text file and then set to textview?

I am trying to save a string to a txt file in the onPause method, and then later set the saved string to a textview, but I am having problems. I don't necessary need to set the string in the onResume method. Primary problem is getting IO to work in Android, thanks.

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

Upvotes: 0

Views: 1162

Answers (1)

Romain Piel
Romain Piel

Reputation: 11177

If you want to make variables persistent across sessions, you'd better use SharedPreference instead of storing it into a text file.

Upvotes: 3

Related Questions