How do I get the SharedPreferences from a PreferenceActivity in Android?

后端 未结 6 1150
梦如初夏
梦如初夏 2020-11-22 11:28

I am using a PreferenceActivity to show some settings for my application. I am inflating the settings via a xml file so that my onCreate (and complete class methods) looks l

6条回答
  •  無奈伤痛
    2020-11-22 12:30

    Declare these methods first..

    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();
    }
    
    public static String getPref(String key, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, null);
    }
    

    Then call this when you want to put a pref:

    putPref("myKey", "mystring", getApplicationContext());
    

    call this when you want to get a pref:

    getPref("myKey", getApplicationContext());
    

    Or you can use this object https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo which simplifies everything even further

    Example:

    TinyDB tinydb = new TinyDB(context);
    
    tinydb.putInt("clickCount", 2);
    tinydb.putFloat("xPoint", 3.6f);
    tinydb.putLong("userCount", 39832L);
    
    tinydb.putString("userName", "john");
    tinydb.putBoolean("isUserMale", true); 
    
    tinydb.putList("MyUsers", mUsersArray);
    tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);
    

提交回复
热议问题