Androidストレージ:sharedpreferencesストレージMap

4163 ワード

最近突然プロジェクトで使用された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;
	}