package ***.utils;
import android.content.Context;
import android.content.SharedPreferences;
/**
* date : 2017/8/7
* author : bianyaoyao
* Description :SharedPreferences存储工具类
*/
public class PrefUtils {
private static String name = "Config";
public static void putBoolean(Context ctx, String key, boolean value) {
SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
sp.edit().putBoolean(key, value).commit();
}
public static boolean getBoolean(Context ctx, String key, boolean defValue) {
SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
return sp.getBoolean(key, defValue);
}
public static void putString(Context ctx, String key, String value) {
SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
sp.edit().putString(key, value).commit();
}
public static String getString(Context ctx, String key, String defValue) {
SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
return sp.getString(key, defValue);
}
public static void putInt(Context ctx, String key, int value) {
SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
sp.edit().putInt(key, value).commit();
}
public static int getInt(Context ctx, String key, int defValue) {
SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
return sp.getInt(key, defValue);
}
//删除某个键值对
public static void remove(Context ctx, String key) {
SharedPreferences sp = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
sp.edit().remove(key).commit();
}
}
关于mode参数 一般都取MODE_PRIVATE,这里的MODE_PRIVATE 和openFileOutput方法里的MODE_PRIVATE 是一个意思。官方已经废除了MODE_WORLD_READABLE 和 MODE_WORLD_WRITEABLE 这两个参数意思分别是允许其他应用读取和写入我们的sharedPreferences,官方也是为用户的安全着想
使用:
PrefUtils.putString(LoginActivity.this, "id", "21u34445555");
PrefUtils.getString(LoginActivity.this, "id", "");
当然,上面的String 类型的id 字段可以新建一个文件 ,避免字符串过长拼写错误引起的尴尬问题
public interface GlobalConstants {
String PREF_ID = "id";
}
PrefUtils.getString(LoginActivity.this, GlobalConstants.PREF_ID, "");