Search code examples
androidsharedpreferencessaving-data

How to read from SharedPreference file android


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.


Solution

  • 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"