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

来源:互联网 发布:oracle12c连接数据库 编辑:程序博客网 时间:2024/06/10 00:20

简要的介绍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", "没有获取到数据");

0 0