SharedPreferences儲存各種型別的資料
阿新 • • 發佈:2019-02-04
/** * 專門訪問和設定SharePreference的工具類, 儲存和配置一些設定資訊 */ public class PrefUtils { private static final String SHARE_PREFS_NAME = "sp"; public static void putBoolean(Context ctx, String key, boolean value) { SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME, Context.MODE_PRIVATE); pref.edit().putBoolean(key, value).commit(); } public static boolean getBoolean(Context ctx, String key, boolean defaultValue) { SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME, Context.MODE_PRIVATE); return pref.getBoolean(key, defaultValue); } public static void putString(Context ctx, String key, String value) { SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME, Context.MODE_PRIVATE); pref.edit().putString(key, value).commit(); } public static String getString(Context ctx, String key, String defaultValue) { SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME, Context.MODE_PRIVATE); return pref.getString(key, defaultValue); } public static void putInt(Context ctx, String key, int value) { SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME, Context.MODE_PRIVATE); pref.edit().putInt(key, value).commit(); } public static int getInt(Context ctx, String key, int defaultValue) { SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME, Context.MODE_PRIVATE); return pref.getInt(key, defaultValue); } }
進階可以看這個:http://blog.csdn.net/crazymo_/article/details/53448189