sharedPreferences 的使用
首选项的使用,一般用于在本地存储交小的数据。用于保存一些常用配置信息文章最后有一个对首选项的封装,可以自己添加其他存储类型
获取首选项的两种方式:
- 调用Context对象的 getSharedPreferences()
- 调用Activity对象的 getPreference()
两种方式的区别:
- 通过getSharePreferences()方法获得的实例对象可以被整个应用程序公用
- 通过getPreference()方法获得的实例对象只能在当前Activity中使用
sharedPreferences 有四种操作模式:
- Context.MODE_APPEND 该模式首先检查文件是否存在,存在则直接追加内容,如果不存在则先创建;
- Context.MODE_PRIVATE 该模式为私有模式,也是默认模式,只能被本身的应用访问,写入的内容会覆盖前面的内容
- Context.MODE_WORLD_READABLE 全局可读,可以被其他应用读取;
- Context.MODE_WORLD_WRITEABLE 标识当前其他应用可以写入文件;
使用步骤:
获取实例对象
SharedPreferences sp = getSharedPreferences("fileName",Context.MODE_PRIVATE);
获取编辑器
Editor editor = sp.editor();
存入相关数据
String userName = "nuomi";
String passWord = "nuomi"
editor.put("name",userName);
editor.put("passWord",passWord);
edttor.commit();
- 取出相关数据使用
SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
String name=preferences.getString("name", "defaultname");
String age=preferences.getString("passWord", "0")
获取方法的第二个参数为取不到的时候的默认值;
为了使用方便我们可以直接将首选项进行封装,将具体实现都封装起来;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class SPUtils {
private static SharedPreferences getSharedPreference(Context context) {
return context.getSharedPreferences("config", Context.MODE_PRIVATE);
}
/**
* 这个静态方法只能存放boolean,String
*
* @param context
* @param key
* @param value
*/
public static void put(Context context, String key, Object value) {
Editor editor = getSharedPreference(context).edit();
if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
}
if (value instanceof String) {
editor.putString(key, (String) value);
}
editor.commit();
}
/**
*
* @param context
* @param key
* @return 布尔值默认为false
*/
public static boolean getBoolean(Context context, String key) {
SharedPreferences sp = getSharedPreference(context);
return sp.getBoolean(key, false);
}
/**
*
* @param context
* @param key
* @return 字符串默认为""
*/
public static String getString(Context context, String key) {
SharedPreferences sp = getSharedPreference(context);
return sp.getString(key, "");
}
}