android sharepreferences 小工具类,可以参考下或是提下更好的建议

简要的介绍sharepreferences的参数


//在实例化SharedPreferences对象,参数1是存储文件的名称,参数2是文件的打开方式,当文件不存在时,直接创建,如果存在,则直接使用

//第二个参数  
//MODE_PRIVATE,只读,只能被自己的应用程序访问
//MODE_WORLD_READABLE,可读,除了自己访问外还可以被其它应该程序读取
//MODE_WORLD_WRITEABLE,可写,除了自己访问外还可以被其它应该程序读取和写入
SharedPreferences mySharePreferences =getSharedPreferences("test", Activity.MODE_PRIVATE); 


小工具类

public class SPUtils {

public static final String  USE_TO= "use_to";//保存的参数意义

//设置string类型
public static void setValue(Context context,String name,String key, String value) {
SharedPreferences sp = context.getSharedPreferences(name, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value);
editor.commit();
}

public static String getValues(Context context,String name, String key, String defValue) {
SharedPreferences sp = context.getSharedPreferences(name, Activity.MODE_PRIVATE);
return sp.getString(key, defValue);
}

//设置boolean类型
public static void setValue(Context context,String name, String key, boolean value) {
SharedPreferences sp = context.getSharedPreferences(name, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(key, value);
editor.commit();
}

public static boolean getValues(Context context,String name, String key, boolean defValue) {
SharedPreferences sp = context.getSharedPreferences(name, Activity.MODE_PRIVATE);
return sp.getBoolean(key, defValue);
}

//设置long类型
public static void setValue(Context context,String name, String key, long value) {
SharedPreferences sp = context.getSharedPreferences(name, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putLong(key, value);
editor.commit();
}

public static long getValues(Context context,String name, String key, long defaultValues) {
SharedPreferences sp = context.getSharedPreferences(name, Activity.MODE_PRIVATE);
return sp.getLong(key, defaultValues);
}

//设置int类型
public static void setValue(Context context,String name, String key, int value) {
SharedPreferences sp = context.getSharedPreferences(name, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(key, value);
editor.commit();
}

public static int getValues(Context context,String name, String key, int defaultValues) {
SharedPreferences sp = context.getSharedPreferences(name, Activity.MODE_PRIVATE);
return sp.getInt(key, defaultValues);
}
}



sp小工具类的调用

设置值

SPUtils.setValue(this, SPUtils.USE_TO, "name", "testSPUtils");

获取值

String name=SPUtils.getValues(this, SPUtils.USE_TO, "name", "没有获取到数据");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值