Search code examples
androidpreferences

Using shared preferences (Android)


I am trying to save some data in shared preferences on Android and as the following page says (http://developer.android.com/guide/topics/data/data-storage.html#pref), I should write some code like the code shown bellow inside onCreate() method:

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_tablet);

    //Restore preferences
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    boolean silent = settings.getBoolean("silentMode", false);
    setSilent(silent);
}

The problem is that the last line:

 setSilent(silent);

gives an error shown as:

The method setSilent(boolean) is undefined for the type MainActivity

What should I do to solve this?

Thank you!


Solution

  • To save a value in using sharedpreferences:

    SharedPreferences pref = this.getSharedPreferences("Test",0);
    Editor editor = pref.edit();
    editor.putString("VALUE", value);
    editor.commit();
    

    And get it like that:

    SharedPreferences prfs = getSharedPreferences("Test", Context.MODE_PRIVATE);
    String v= prfs.getString("VALUE", "");