Android封装SharedPreferences工具类

时间:2021-10-06 08:57:49

工具类基本功能说明:
1、保存基本数据类型数据;
2、读取基本数据类型数据;
3、依据key删除对应value;
4、清除SharedPreferences缓存数据静态方法;

package helper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;

public class SharedPreferenceHelper {

public static final String SHARED_PREFERENCES = "Study";

/**
* 保存基本数据类型的数据
* @param context
* @param key
* @param value
*/

@SuppressLint("CommitPrefEdits")
public static void saveValue(Context context, String key, Object value) {

SharedPreferences.Editor editor = context.getSharedPreferences(SHARED_PREFERENCES, 0).edit();

if (!TextUtils.isEmpty(key) && value != null) {

if (value instanceof String) {
editor.putString(key, (String)value);

} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);

} else if (value instanceof Long) {
editor.putLong(key, (Long) value);

} else if (value instanceof Float) {
editor.putFloat(key, (Float) value);

} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean)value);

}
}
}

/**
* 读取基本数据类型的数据
* @param context
* @param key
* @param classT
* @return
*/

@SuppressWarnings("unchecked")
public static <T> T getValue(Context context, String key, Class<T> classT) {

SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES, 0);

if (!TextUtils.isEmpty(key) && classT != null) {
String className = classT.getSimpleName();

if ("String".equals(className)) {
return (T) sharedPreferences.getString(key, null);

} else if ("Integer".equals(className)) {
return (T) Integer.valueOf(sharedPreferences.getInt(key, -1));

} else if ("Long".equals(className)) {
return (T) Long.valueOf(sharedPreferences.getLong(key, -1));

} else if ("Float".equals(className)) {
return (T) Float.valueOf(sharedPreferences.getFloat(key, -1));

} else if ("Boolean".equals(className)) {
return (T) Boolean.valueOf(sharedPreferences.getBoolean(key, false));

}
}

return null;
}

/**
* 删除值
* @param context
* @param key
*/

@SuppressLint("CommitPrefEdits")
public static void deleteValue(Context context, String key) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES, 0);
Editor editor = sharedPreferences.edit();
editor.remove(key);
}

/**
* 清除缓存数据
* @param context
*/

@SuppressLint("CommitPrefEdits")
public static void clearData(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES, 0);
Editor editor = sharedPreferences.edit();
editor.clear();
}
}