###新建一个SpUtil工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| /** * Created by xpf on 2017/03/25 :) * Function: sp存储的工具类 */ public class SpUtil {
private static final String ANLEKE = "anleke";
private SpUtil() { }
private static SpUtil instace = new SpUtil(); private static SharedPreferences mSp = null;
public static SpUtil getInstace() {
if (mSp == null) { mSp = MyApplication.getContext().getSharedPreferences(ANLEKE, Context.MODE_PRIVATE); } return instace; }
/** * 保存数据 * * @param key 键 * @param value 值 */ public void save(String key, Object value) {
if (value instanceof String) { mSp.edit().putString(key, (String) value).commit(); } else if (value instanceof Boolean) { mSp.edit().putBoolean(key, (Boolean) value).commit(); } else if (value instanceof Integer) { mSp.edit().putInt(key, (Integer) value).commit(); } }
// 读取String类型数据 public String getString(String key, String defValue) { return mSp.getString(key, defValue); }
// 读取boolean类型数据 public boolean getBoolean(String key, boolean defValue) { return mSp.getBoolean(key, defValue); }
// 读取int类型数据 public int getInt(String key, int defValue) { return mSp.getInt(key, defValue); }
}
|
###注:在MyApplication中获取上下文
1 2 3 4 5 6 7 8 9 10 11 12
| private static Context mContext;
@Override public void onCreate() { super.onCreate(); mContext = this; }
// 获取全局上下文 public static Context getContext() { return mContext; }
|