安卓存储之SharedPreference

xiaoxiao2021-02-28  13

1.键值对方式存储。

2.Android6.0之后只有一种模式,MODE_PRIVATE。

3.三种得到SharedPreferences对象

4.SharedPreference存储数据

eg:

SharedPreferences.Editor editor=getSharedPreferences("File_name",MODE_PRIVATE).edit();

editor.putInt("age",22);

editor.apply();

5.SharedPreference读取数据

eg:

SharedPreferences pref=getSharedPreferences("File_name",MODE_PRIVATE);

int age=pref.getInt("age",0);

6.SharedPreference的工具类的封装(参考网上比较简洁的封装)

public class SharedPreferencesUtils { private static final String FILE_NAME="sp"; public static void writeData(Context context,String key,Object value){ String dataType=value.getClass().getSimpleName(); SharedPreferences.Editor editor=context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE).edit(); if ("Integer".equals(dataType)){ editor.putInt(key, (Integer) value); }else if ("String".equals(dataType)){ editor.putString(key, (String) value); }else if ("Boolean".equals(dataType)){ editor.putBoolean(key, (Boolean) value); }else if ("Float".equals(dataType)){ editor.putFloat(key, (Float) value); }else if ("Long".equals(dataType)){ editor.putLong(key, (Long) value); } editor.apply(); } public static Object getData(Context context,String key,Object value) { Object object=null; String dataType=value.getClass().getSimpleName(); SharedPreferences sp=context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); if ("Integer".equals(dataType)){ object=sp.getInt(key, (Integer) value); }else if ("String".equals(dataType)){ object=sp.getString(key, (String) value); }else if ("Boolean".equals(dataType)){ object=sp.getBoolean(key, (Boolean) value); }else if ("Float".equals(dataType)){ object=sp.getFloat(key, (Float) value); }else if ("Long".equals(dataType)){ object=sp.getLong(key, (Long) value); } return object; } }

注:equals()的用法,常量放在前面,避免出现变量值为空的报错。

文件位置:http://download.csdn.net/detail/ling1008123/9895301

转载请注明原文地址: https://www.6miu.com/read-800188.html

最新回复(0)