建一个ToolUtils工具类,然后在里面分别写存和取的逻辑方法
public class ToolUtils {
/**
* setLeftList 设置缓存,存数据
* @param context
* @param key
* @param list
* @author wang 8/31
*/
public static void setLeftList(Context context, String key,List<Map<String,Object>> list){
JSONArray mJsonArray = new JSONArray();
for(int i=0;i<list.size();i++){
Map<String,Object> itemMap = list.get(i);
Iterator<Map.Entry<String,Object>> iterator = itemMap.entrySet().iterator();
JSONObject object = new JSONObject();
while (iterator.hasNext()){
Map.Entry<String,Object> entry = iterator.next();
try {
object.put(entry.getKey(),entry.getValue());
}catch (JSONException je){
je.printStackTrace();
}
}
mJsonArray.put(object);
}
SharedPreferences sharedPreferences = context.getSharedPreferences(key,context.MODE_PRIVATE);
SharedPreferences.Editor shareEditor = sharedPreferences.edit();
shareEditor.putString(key,mJsonArray.toString());
shareEditor.commit();
}
/**
* getLeftList 取数据
* @param context
* @param key
* @return
* @author wang 8/31
*/
public static List<Map<String,Object>> getLeftList(Context context,String key){
List<Map<String, Object>> list = new ArrayList<>();
SharedPreferences sharedPreferences = context.getSharedPreferences(key,context.MODE_PRIVATE);
String result = sharedPreferences.getString(key,"");
try{
JSONArray array = new JSONArray(result);
for (int i=0;i<array.length();i++){
JSONObject jsonItem = array.getJSONObject(i);
Map<String,Object> mapItem = new HashMap<>();
JSONArray names = jsonItem.names();
if(names !=null){
for(int j=0;j<names.length();j++){
String name = names.getString(j);
String value = jsonItem.getString(name);
mapItem.put(name,value);
}
}
list.add(mapItem);
}
}catch (JSONException je){
je.printStackTrace();
}
return list;
}
}
使用
ToolUtils.setLeftList(getContext(), "leftList", left_list); //存数据
List<Map<String,Object>> list = ToolUtils.getLeftList(getContext(),"leftList"); //从缓存中取数据