Introduction to SharedPreferences
SharedPreferences is a data storage method in android. It is stored in the memory in the form of xml in the form of key-value key-value pairs. The files are stored in the /data/data//shared_prefs directory. SharedPreferences
initialization
getSharedPreferences(name,mode) The
name and mode parameters represent memory space naming and access permission mode
name respectively. Memory space naming is to open up a storage space belonging to your app in memory.
Mode access permission
MODE_APPEND : additional storage
MODE_PRIVATE : private Storage
MODE_WORLD_READABLE open storage mode other apps can read
MODE_WORLD_WRITEABLE open storage mode other apps can write and get editing objects
Common methods
SharedPreferences.Editor edit = sp.edit();
edit.clear();//Clear data
edit.putString();//Save string
edit.putInt(); //Save int
edit.putLong() ; //Store in long
edit.putBoolean(); //Store in boolean
edit.putFloat(); //Store in float
edit.putStringSet();//Store in set
sp.getString(); //Get string
sp .getInt(); // take int
sp.getBoolean();// take boolean
sp.getLong(); // take long
sp.getAll(); // take map
本人封装的sp 管理工具
public class SPUtils {
/**
* sq 构造 持有context 对象
* @param context
*/
public static SharedPreferences sp;
public static Context context;
public SPUtils(Context context) {
this.context = context;
if (sp==null){
sp = context.getSharedPreferences(Constant.SPKEY, Context.MODE_PRIVATE);
}
}
/**
* getString/char
* @param key 字段名
* @return value 返回值
*/
public static String getString(String key){
String value = sp.getString(key, "");
if (!TextUtils.isEmpty(value)){
return value;
}else {
return Constant.BACKERROR+"";
}
}
/**
* getInt方法
* @param key 字段名
*
* @return value int返回值
*/
public static int getInt(String key){
int value = sp.getInt(key, 0);
if (value!=0){
return value;
}else {
return Constant.BACKERROR;
}
}
/**
* getLong 方法
*
* @param key 字段名
* @return Long返回值
*/
public static Long getLong(String key){
Long value = sp.getLong(key, 0);
if (value!=0){
return value;
}else {
return Long.valueOf(Constant.BACKERROR);
}
}
/**
* putString 方法
*
* @param key 字段名
* @param value 字段值
*/
public static void putString(String key,String value){
sp.edit().putString(key,value).commit();
}
/**
* putInt 方法
*
* @param key 字段名
* @param value 字段值
*/
public static void putInt(String key,int value){
sp.edit().putInt(key,value).commit();
}
/**
* putLong 方法
*
* @param key 字段名
* @param value 字段值
*/
public static void putLong(String key,Long value){
sp.edit().putLong(key,value).commit();
}
// 清除数据
public static void clearSpSpace(){
sp.edit().clear().commit();
}
}