封装SharedPreferences的工具类

时间:2022-03-05 06:17:45
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

/**
* 封装SharedPreferences的工具类
* int/float/double/boolean/String
* 1. 保存数据
* putString(String key, String value)
* putInt(String key, int value)
* putBoolean(String key, boolean value)
* 2. 读取数据
* getString(String key, String defValue)
* getInt(String key, int defValue)
* getBoolean(String key, boolean defValue)
* 3. 移除数据
* remove(String key)
*/
public class SpUtils {//单列
//sp设置成单例模式:全局只有一个该对象
private static SharedPreferences sp;
private static SpUtils instance = new SpUtils();

private SpUtils() {
}

public static SpUtils getInstance(Context context) {
if (sp == null) {//懒汉式
sp = context.getSharedPreferences("ms", Context.MODE_PRIVATE);
}
return instance;
}

/**
* 把数据保存到SharedPerference
*/
public void save(String key, Object value) {
//获取Editor对象
Editor editor = sp.edit();
if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else if (value instanceof Float) {
editor.putFloat(key, (Float) value);
}
//提交保存数据
editor.commit();
}

/**
* 读取数据
*/
public String getString(String key, String defValue) {
return sp.getString(key, defValue);
}

public int getInt(String key, Integer defValue) {
return sp.getInt(key, defValue);
}

public boolean getBoolean(String key, Boolean defValue) {
return sp.getBoolean(key, defValue);
}

public double getFloat(String key, Float defValue) {
return sp.getFloat(key, defValue);
}

/**
* 移除数据
*/
public void remove(String key) {
sp.edit().remove(key).commit();
}
}