0

In my MainActivity, I have written some code which I assume creates a file and saves a value in that file.

public static final String WHAT_I_WROTE = null;
 public void sendMessage(View view) {
    EditText editText = (EditText) findViewById(R.id.editText);
    String message = editText.getText().toString();

    //creates new SharedPreference?
    SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);

    //writes to the preferences file called saved_text?
    SharedPreferences.Editor writer = saver.edit();
    writer.putString(WHAT_I_WROTE, message);
    writer.commit();
}

In another activity, I want to be able to read the message and display it but when I try this, it cannot resolve the symbol "saver".

String text_for_display = saver.getString(WHAT_I_WROTE);

What is the mistake I have made here and how do I correct it to read the saved string?

Thanks.

Aswin Abraham
  • 139
  • 1
  • 7

4 Answers4

0

In another activity you have to again initalize the Shared preference.

    SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
    String text_for_display = saver.getString(WHAT_I_WROTE),"any_default_value";

WHAT_WROTE = "anyText"

Chirag
  • 56,621
  • 29
  • 151
  • 198
0

Add this to the other activity you have:

SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);

then read it like this

String myValue = saver.getString("saved_text", "default_value");
Vincent
  • 64
  • 8
0

Setting values in preference is like,

SharedPreferences.Editor editor = getSharedPreferences("saved_text", MODE_PRIVATE).edit();
 editor.putString("WHAT_I_WROTE", message);
 editor.commit();

Retrieve the data like,

    SharedPreferences prefs = getSharedPreferences("saved_text", MODE_PRIVATE); 
String text_for_display = prefs.getString("WHAT_I_WROTE", null);
Sunisha Guptan
  • 1,555
  • 17
  • 44
0

Don't forget to put "context" before "getSharedPreferences" if necessary.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
Silvain
  • 21
  • 3