SharedPreferencesUtil sharedPreferences工具类

项目中少不了用sharedPreferences来存储数据,为了新项目方便,我们直接定义出SharedPreferencesUtil

  • 单例模式
  • 添加(putXX)
  • 删除(reomve)
  • 获取(getXX)


public class SharedPreferencesUtil {


private SharedPreferences sp;

private static SharedPreferencesUtil spUtil;

private SharedPreferencesUtil(Context context){
sp = PreferenceManager.getDefaultSharedPreferences(context);
}

public static SharedPreferencesUtil getSharedPreferences(Context context){
if(spUtil == null){
spUtil = new SharedPreferencesUtil(context);
}
return spUtil;
}

public void remove(String key){
if(sp != null){
sp.edit().remove(key).commit();
}
}

public void putBoolean(String key, boolean value){
if(sp != null){
sp.edit().putBoolean(key, value).commit();
}
}

public void putFloat(String key, float value){
if(sp != null){
sp.edit().putFloat(key, value).commit();
}
}

public void putInt(String key, int value){
if(sp != null){
sp.edit().putInt(key, value).commit();
}
}

public void putLong(String key, long value){
if(sp != null){
sp.edit().putLong(key, value).commit();
}
}

public void putString(String key, String value){
if(sp != null){
sp.edit().putString(key, value).commit();
}
}

public String getString(String key, String defValue){
String value = null;
if(sp != null){
value = sp.getString(key, defValue);
}
return value;
}

public boolean getBoolean(String key, boolean defValue){
boolean value = false;
if(sp != null){
value = sp.getBoolean(key, defValue);
}
return value;
}

public int getInt(String key, int defValue){
int value = 0;
if(sp != null){
value = sp.getInt(key, defValue);
}
return value;
}

public long getLong(String key, long defValue){
long value = 0;
if(sp != null){
value = sp.getLong(key, defValue);
}
return value;
}

public void clearAll(){
if(sp != null){
sp.edit().clear().commit();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值