what is the Best way to use shared preferences between activities

后端 未结 4 822
悲哀的现实
悲哀的现实 2020-12-08 16:13

I have a user preference in my app, which gets used by different activities. I would like to know the best way to utilize those preferences between different activities in m

4条回答
  •  感动是毒
    2020-12-08 16:20

    Sending shared preferences through intents seems overcomplicated. You could wrap the shared preferences with something like the below and call the methods directly from your activities:

    public class Prefs {
        private static String MY_STRING_PREF = "mystringpref";
        private static String MY_INT_PREF = "myintpref";
    
        private static SharedPreferences getPrefs(Context context) {
            return context.getSharedPreferences("myprefs", 0);
        }
    
        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, 42);
        }
    
        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();
        }
    }
    

提交回复
热议问题