[Solved] How to use shared preference data in different classes in android?


PREFS_NAME is the value you stored in shared preference.

 public static final String PREFS_NAME = "MyPrefsFile";    

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

Look at Restoring preferences

Edited:To use it among all classes i.e. setter getter method.Perfect use of OOPS.You can call the value from any class thats 1-line job

Make a normal class name as ReturningClass.

public class ReturningClass {

private static String MY_STRING_PREF = "mystringpref";

private static String MY_INT_PREF = "shareduserid";

public static SharedPreferences getPrefs(Context context) {


    return context.getSharedPreferences("UserNameAcrossApplication", context.MODE_PRIVATE);

}

public static String getMyStringPref(Context context) {

    return getPrefs(context).getString(MY_STRING_PREF, "default");
}

public static int getMyIntPref(Context context) {

    return getPrefs(context).getInt(MY_INT_PREF, 0);
}

public static void setMyStringPref(Context context, String value) {
    // perform validation etc..
    getPrefs(context).edit().putString(MY_STRING_PREF, value).commit();
}

public static void setMyIntPref(Context context, int value) {
    // perform validation etc..
    getPrefs(context).edit().putInt(MY_INT_PREF, value).commit();
}

Set your value by calling

  ReturningClass.setMyIntPref(mContext,22);

Once You have set your sharedPreference.Then just call this method.Just pass the context.from your class

 int usersharedpreference=ReturningClass.getMyIntPref(mContext);

0

solved How to use shared preference data in different classes in android?