当前位置: 移动技术网 > IT编程>移动开发>Android > Android存储:sharedpreferences存储一个Map

Android存储:sharedpreferences存储一个Map

2018年04月11日  | 移动技术网IT编程  | 我要评论

四胞胎父亲称为孩子上学欠老板46万,富贵荣华 府天,大玩家小斋

最近突然项目中用到的sharedpreferences来存储一个Map集合,特来此记录一下可以让更多的小伙伴知道一下。

这里只是一个记录单独存储map的,可以直接用

String?examtype = "examtype";

//存储Map

 


	public static void setMap(Context context, Map map) {
   		 if (map != null) {
       			 JSONStringer jsonStringer = new JSONStringer();
      				  try {
        			    jsonStringer.array();
          				  for (String string : map.keySet()) {
          				    jsonStringer.object();
            				    jsonStringer.key("year");
            				    jsonStringer.value(string);
             				    jsonStringer.key("month");
            				    jsonStringer.value(map.get(string));
               				    jsonStringer.endObject();
      				      }
    				        jsonStringer.endArray();
   					     } catch (JSONException e) {
 					           e.printStackTrace();
 				       }
 				       SharedPreferences sp = context.getSharedPreferences("map", Context.MODE_PRIVATE);
   				     sp.edit().putString(examtype, jsonStringer.toString()).apply();
  		  }
	}


	//获取Map的值

	
	public static Map getMap(Context context) {
  		  Map examMap = new HashMap<>();
  		  SharedPreferences sp = context.getSharedPreferences("map", Context.MODE_PRIVATE);
  		  String map = sp.getString(examtype, "");
  		  if (map.length() > 0) {
    		    JSONTokener jsonTokener = new JSONTokener(map);
      		  try {
        	    JSONArray jsonArray = (JSONArray) jsonTokener.nextValue();
        		    for (int i = 0; i < jsonArray.length(); i++) {
          		      JSONObject jsonObject = jsonArray.getJSONObject(i);
          		      examMap.put(jsonObject.getString("year"), jsonObject.getString("month"));
         		   }
    		    } catch (JSONException e) {
      		      e.printStackTrace();
      			  }
  		  }
   		 return examMap;
	}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网