用途:存放标記性資料和設定資訊
功能:
1.儲存字元串:saveString
2.傳回字元串:getString
3.儲存布爾:saveBoolean
4.傳回布爾:getBoolean
5.儲存int:saveInt
6.傳回int:getInt
7.儲存float:saveFloat
8.傳回float:getFloat
9.查詢某個key是否已經存在:contains
public class SharedPreferencesUtils {
public static final String SP_NAME = "config";
private static SharedPreferences sp;
/**
* 儲存字元串
*
* @param context
* @param key
* @param value
*/
public static void saveString(Context context, String key, String value) {
if (sp == null){
sp = context.getSharedPreferences(SP_NAME, 0);
}
sp.edit().putString(key, value).commit();
}
/**
* 傳回字元串
*
* @param context
* @param key
* @param defValue 預設值
* @return
*/
public static String getString(Context context, String key, String defValue) {
if (sp == null){
sp = context.getSharedPreferences(SP_NAME, 0);
}
return sp.getString(key, defValue);
}
/**
* 儲存布爾
*
* @param context
* @param key
* @param value
*/
public static void saveBoolean(Context context, String key, boolean value) {
if (sp == null){
sp = context.getSharedPreferences(SP_NAME, 0);
}
sp.edit().putBoolean(key, value).commit();
}
/**
* 傳回布爾
*
* @param context
* @param key
* @param defValue 預設值
* @return
*/
public static boolean getBoolean(Context context, String key, boolean defValue) {
if (sp == null){
sp = context.getSharedPreferences(SP_NAME, 0);
}
return sp.getBoolean(key, defValue);
}
/**
* 儲存int
*
* @param context
* @param key
* @param value
*/
public static void saveInt(Context context, String key, int value) {
if (sp == null){
sp = context.getSharedPreferences(SP_NAME, 0);
}
sp.edit().putInt(key, value).commit();
}
/**
* 傳回int
*
* @param context
* @param key
* @param defValue 預設值
* @return
*/
public static int getInt(Context context, String key, int defValue) {
if (sp == null){
sp = context.getSharedPreferences(SP_NAME, 0);
}
return sp.getInt(key, defValue);
}
/**
* 儲存float
*
* @param context
* @param key
* @param value
*/
public static void saveFloat(Context context, String key, float value) {
if (sp == null){
sp = context.getSharedPreferences(SP_NAME, 0);
}
sp.edit().putFloat(key, value).commit();
}
/**
* 傳回float
*
* @param context
* @param key
* @param defValue 預設值
* @return
*/
public static float getFloat(Context context, String key, float defValue) {
if (sp == null){
sp = context.getSharedPreferences(SP_NAME, 0);
}
return sp.getFloat(key, defValue);
}
/**
* 查詢某個key是否已經存在
*
* @param context
* @param key
* @return
*/
public static boolean contains(Context context, String key) {
if (sp == null){
sp = context.getSharedPreferences(SP_NAME, 0);
}
return sp.contains(key);
}
}