/**
* 使用方法:存调用SharePrefUtil.saveInt("上下文","存键","存值");
* 取调用SharePrefUtil.getInt("上下文","要取数值的键","默认值");
* 清空调用SharePrefUtil.clear("上下文");
*/
public class SharePrefUtil {
private static Stringtag = SharePrefUtil.class.getSimpleName();
private finalstatic String SP_NAME ="config";
private static SharedPreferencessp;
/**
* 保存布尔值
*
* @param context
* @param key
* @param value
*/
public staticvoid saveBoolean(Context context, Stringkey, boolean value) {
if (sp ==null)
sp =context.getSharedPreferences(SP_NAME, 0);
sp.edit().putBoolean(key,value).commit();
}
/**
* 保存字符串
*
* @param context
* @param key
* @param value
*/
public staticvoid saveString(Context context, Stringkey, String value) {
if (sp ==null)
sp =context.getSharedPreferences(SP_NAME, 0);
sp.edit().putString(key,value).commit();
}
/**
* 保存long型
*
* @param context
* @param key
* @param value
*/
public staticvoid saveLong(Context context, Stringkey, long value) {
if (sp ==null)
sp =context.getSharedPreferences(SP_NAME, 0);
sp.edit().putLong(key,value).commit();
}
/**
* 保存int型
*
* @param context
* @param key
* @param value
*/
public staticvoid saveInt(Context context, Stringkey, int value) {
if (sp ==null)
sp =context.getSharedPreferences(SP_NAME, 0);
sp.edit().putInt(key,value).commit();
}
/**
* 保存float型
*
* @param context
* @param key
* @param value
*/
public staticvoid saveFloat(Context context, Stringkey, float value) {
if (sp ==null)
sp =context.getSharedPreferences(SP_NAME, 0);
sp.edit().putFloat(key,value).commit();
}
/**
* 获取字符值
*
* @param context
* @param key
* @param defValue
* @return
*/
public static String getString(Contextcontext, String key, String defValue) {
if (sp ==null)
sp =context.getSharedPreferences(SP_NAME, 0);
return sp.getString(key, defValue);
}
/**
* 获取int值
*
* @param context
* @param key
* @param defValue
* @return
*/
public staticint getInt(Context context, Stringkey, int defValue) {
if (sp ==null)
sp =context.getSharedPreferences(SP_NAME, 0);
return sp.getInt(key, defValue);
}
/**
* 获取long值
*
* @param context
* @param key
* @param defValue
* @return
*/
public staticlong getLong(Context context, Stringkey, long defValue) {
if (sp ==null)
sp =context.getSharedPreferences(SP_NAME, 0);
return sp.getLong(key, defValue);
}
/**
* 获取float值
*
* @param context
* @param key
* @param defValue
* @return
*/
public staticfloat getFloat(Context context, Stringkey, float defValue) {
if (sp ==null)
sp =context.getSharedPreferences(SP_NAME, 0);
return sp.getFloat(key, defValue);
}
/**
* 获取布尔值
*
* @param context
* @param key
* @param defValue
* @return
*/
public staticboolean getBoolean(Context context, Stringkey,
booleandefValue) {
if (sp ==null)
sp =context.getSharedPreferences(SP_NAME, 0);
return sp.getBoolean(key, defValue);
}
public staticvoid clear(Context context) {
if (sp ==null)
sp =context.getSharedPreferences(SP_NAME, 0);
sp.edit().clear().commit();
}
}
sharedPrefrence 合理使用 点击打开链接
sharedPrefrence 使用出现的一些问题 点击打开链接