使用环境:
项目中使用到缓存文件,但是不满足常规存储,需要用到存储List<bean>
使用方法:
1 讲list<Bean> 通过Gson转换为Json字符串,存储在sp缓存中
SpUtils.put(Utils.getContext(),"module_key",new Gson().toJson(listSpBeans));
2 将json字符串取出,通过解析为指定类型进行解析还原List<Bean>
String res = (String) SpUtils.get(Utils.getContext(), "module_key", "");
if (!TextUtils.isEmpty(res)) {
listType = new TypeToken<List<SearchSongBean.ResultBean>>() {
}.getType();
gson = new Gson();
List<Bean> listSpBeans = gson.fromJson(res, listType);
}
3 下面关于SpUtils的代码,懒得封装的朋友可以直接复制走
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import com.goldze.mvvmhabit.app.AppApplication;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by SensYang on 2019/02/27 10:32
*/
public class SpUtils {
public SpUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
public static final String FILE_NAME = "ma_object";
public static String put(String key, Object object){
SharedPreferences sp = AppApplication.getInstance().getApplicationContext().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (object instanceof String) {
editor.putString(key, (String) object);
} else if (object instanceof Integer) {
editor.putInt(key, (Integer) object);
} else if (object instanceof Boolean) {
editor.putBoolean(key, (Boolean) object);
} else if (object instanceof Float) {
editor.putFloat(key, (Float) object);
} else if (object instanceof Long) {
editor.putLong(key, (Long) object);
} else {
editor.putString(key, object.toString());
}
SpUtils.SharedPreferencesCompat.apply(editor);
return key;
}
public static String put(Context context, String key, Object object) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (object instanceof String) {
editor.putString(key, (String) object);
} else if (object instanceof Integer) {
editor.putInt(key, (Integer) object);
} else if (object instanceof Boolean) {
editor.putBoolean(key, (Boolean) object);
} else if (object instanceof Float) {
editor.putFloat(key, (Float) object);
} else if (object instanceof Long) {
editor.putLong(key, (Long) object);
} else {
editor.putString(key, object.toString());
}
SpUtils.SharedPreferencesCompat.apply(editor);
return key;
}
public static Object get(String key, Object defaultObject){
SharedPreferences sp = AppApplication.getInstance().getApplicationContext().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
if (defaultObject instanceof String) {
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer) {
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float) {
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long) {
return sp.getLong(key, (Long) defaultObject);
}
return null;
}
public static Object get(Context context, String key, Object defaultObject) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
if (defaultObject instanceof String) {
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer) {
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float) {
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long) {
return sp.getLong(key, (Long) defaultObject);
}
return null;
}
public static void remove(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
SpUtils.SharedPreferencesCompat.apply(editor);
}
public static void clear(Context context) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
SpUtils.SharedPreferencesCompat.apply(editor);
}
public static boolean contains(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
return sp.contains(key);
}
public static Map<String, ?> getAll(Context context) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
return sp.getAll();
}
private static class SharedPreferencesCompat {
private static final Method sApplyMethod = findApplyMethod();
@SuppressWarnings({"unchecked", "rawtypes"})
private static Method findApplyMethod() {
try {
Class clz = SharedPreferences.Editor.class;
return clz.getMethod("apply");
} catch (NoSuchMethodException e) {
}
return null;
}
public static void apply(SharedPreferences.Editor editor) {
try {
if (sApplyMethod != null) {
sApplyMethod.invoke(editor);
return;
}
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
editor.commit();
}
}
public static void putBean(String key , Object obj){
putBean(AppApplication.getInstance().getApplicationContext(),key,obj);
}
public static void putBean(Context context, String key, Object obj) {
if (obj instanceof Serializable) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
String string64 = new String(Base64.encode(baos.toByteArray(),
0));
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, string64).commit();
} catch (IOException e) {
e.printStackTrace();
}
} else {
throw new IllegalArgumentException(
"the obj must implement Serializble");
}
}
public static Object getBean(String key){
return getBean(AppApplication.getInstance().getApplicationContext(),key);
}
public static Object getBean(Context context, String key) {
Object obj = null;
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
try {
String base64 = sp.getString(key, "");
if (base64.equals("")) {
return null;
}
byte[] base64Bytes = Base64.decode(base64.getBytes(), 1);
ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
obj = ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* 存储List<String>
*
* @param context
* @param key
* List<String>对应的key
* @param strList
* 对应需要存储的List<String>
*/
public static void putStrListValue(Context context, String key,
List<String> strList) {
if (null == strList) {
return;
}
// 保存之前先清理已经存在的数据,保证数据的唯一性
removeStrList(context, key);
int size = strList.size();
putIntValue(context, key + "size", size);
for (int i = 0; i < size; i++) {
putStringValue(context, key + i, strList.get(i));
}
}
/**
* 存储数据(String)
*
* @param context
* @param key
* @param value
*/
private static void putStringValue(Context context, String key, String value) {
SharedPreferences.Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
.edit();
sp.putString(key, value);
sp.commit();
}
/**
* 取出数据(int)
*
* @param context
* @param key
* @param defValue
* 默认值
* @return
*/
private static int getIntValue(Context context, String key, int defValue) {
SharedPreferences sp = context.getSharedPreferences(SETTING,
Context.MODE_PRIVATE);
int value = sp.getInt(key, defValue);
return value;
}
/**
* 取出数据(String)
*
* @param context
* @param key
* @param defValue
* 默认值
* @return
*/
private static String getStringValue(Context context, String key,
String defValue) {
SharedPreferences sp = context.getSharedPreferences(SETTING,
Context.MODE_PRIVATE);
String value = sp.getString(key, defValue);
return value;
}
/**
* 取出List<String>
*
* @param context
* @param key
* List<String> 对应的key
* @return List<String>
*/
public static List<String> getStrListValue(Context context, String key) {
List<String> strList = new ArrayList<String>();
int size = getIntValue(context, key + "size", 0);
//Log.d("sp", "" + size);
for (int i = 0; i < size; i++) {
strList.add(getStringValue(context, key + i, null));
}
return strList;
}
/**
* 清空List<String>所有数据
*
* @param context
* @param key
* List<String>对应的key
*/
public static void removeStrList(Context context, String key) {
int size = getIntValue(context, key + "size", 0);
if (0 == size) {
return;
}
remove(context, key + "size");
for (int i = 0; i < size; i++) {
remove(context, key + i);
}
}
/**
* @Description TODO 清空List<String>单条数据
* @param context
* @param key
* List<String>对应的key
* @param str
* List<String>中的元素String
*/
public static void removeStrListItem(Context context, String key, String str) {
int size = getIntValue(context, key + "size", 0);
if (0 == size) {
return;
}
List<String> strList = getStrListValue(context, key);
// 待删除的List<String>数据暂存
List<String> removeList = new ArrayList<String>();
for (int i = 0; i < size; i++) {
if (str.equals(strList.get(i))) {
if (i >= 0 && i < size) {
removeList.add(strList.get(i));
remove(context, key + i);
putIntValue(context, key + "size", size - 1);
}
}
}
strList.removeAll(removeList);
// 删除元素重新建立索引写入数据
putStrListValue(context, key, strList);
}
/**
* 存储数据(Int)
*
* @param context
* @param key
* @param value
*/
private static void putIntValue(Context context, String key, int value) {
SharedPreferences.Editor sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
.edit();
sp.putInt(key, value);
sp.commit();
}
/** 数据存储的XML名称 **/
public final static String SETTING = "SharedPrefsStrList";
}
更多讨论欢迎来聊: 88627109