How to get value of SharedPreferences android

前端 未结 5 1890
我在风中等你
我在风中等你 2021-01-23 02:41

I\'m trying to use SharedPreferences here is what i do

public void StoreToshared(Object userData){
    SharedPreferences mPrefs = getPreferences(MOD         


        
5条回答
  •  滥情空心
    2021-01-23 03:30

    You can create 2 method:

    // put value
    public static void putPref(String key, String value, Context context) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(key, value);
        editor.commit();
    }
    

    and

    // get value
    public static String getPref(String key, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, null);
    }
    

    then you can put value

    putPref("userinfo", "/** user data json */", getApplicationContext());
    

    and get value

    String data = getPref("userinfo", getApplicationContext());
    

    I hope it can help your problem!

提交回复
热议问题