Android 中 SPUtil工具类如何封装?
时间: 2024-04-29 14:24:05 浏览: 11
SPUtil工具类是用来简化SharedPreferences的操作的,以下是一个简单的封装例子:
```java
public class SPUtil {
private static SharedPreferences sp;
private static SharedPreferences.Editor editor;
private static final String SP_NAME = "config";
public static void init(Context context) {
sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
editor = sp.edit();
}
public static void putString(String key, String value) {
editor.putString(key, value);
editor.apply();
}
public static String getString(String key, String defaultValue) {
return sp.getString(key, defaultValue);
}
public static void putInt(String key, int value) {
editor.putInt(key, value);
editor.apply();
}
public static int getInt(String key, int defaultValue) {
return sp.getInt(key, defaultValue);
}
public static void putBoolean(String key, boolean value) {
editor.putBoolean(key, value);
editor.apply();
}
public static boolean getBoolean(String key, boolean defaultValue) {
return sp.getBoolean(key, defaultValue);
}
public static void clear() {
editor.clear();
editor.apply();
}
}
```
在使用之前需要先调用init方法进行初始化,然后就可以使用put和get方法来进行数据的存取了。另外,为了保证数据的安全性,建议将SP_NAME设置成一个常量,这样可以避免在多处使用时出现错误。