Skip to content Skip to sidebar Skip to footer

Shared Preferences From Other Activity To Be Call With Button

I'm a beginner trying to understand sharedpreferences. Everything is going smoothly as my program of shared preferences run as I want it to be . My inputs are in activity 1 and u

Solution 1:

Store sharedpreference to Constant class and use static variables than set and get values from that class anytime you want.

Setting values in Preference:

MY_PREFS_NAME - a static String variable like: 

publicstaticfinalStringMY_PREFS_NAME="MyPrefsFile";

SharedPreferences.Editoreditor= getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Amit");
 editor.putInt("idName", 888);
 editor.commit();

Retrieve data from preference:

SharedPreferencesprefs= getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 

    StringrestoredText= prefs.getString("text", null);
    if (restoredText != null) {
      Stringname= prefs.getString("name", "No name defined");  //"No name defined" is the default value.intidName= prefs.getInt("idName", 0);    //0 is the default value.
    }

check this answer for more details.

Post a Comment for "Shared Preferences From Other Activity To Be Call With Button"