HashMap을 공유 기본 설정에 저장하는 방법은 무엇입니까?
Android의 공유 기본 설정 에 HashMap 을 어떻게 저장할 수 있습니까?
SharedPreference에 복잡한 객체를 작성하는 것은 권장하지 않습니다. 대신 ObjectOutputStream
내부 메모리에 쓰는 데 사용 합니다.
File file = new File(getDir("data", MODE_PRIVATE), "map");
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
outputStream.writeObject(map);
outputStream.flush();
outputStream.close();
내가 사용하는 Gson
변환에 HashMap
에 String
그것을 저장에 다음과SharedPrefs
private void hashmaptest()
{
//create test hashmap
HashMap<String, String> testHashMap = new HashMap<String, String>();
testHashMap.put("key1", "value1");
testHashMap.put("key2", "value2");
//convert to string using gson
Gson gson = new Gson();
String hashMapString = gson.toJson(testHashMap);
//save in shared prefs
SharedPreferences prefs = getSharedPreferences("test", MODE_PRIVATE);
prefs.edit().putString("hashString", hashMapString).apply();
//get from shared prefs
String storedHashMapString = prefs.getString("hashString", "oopsDintWork");
java.lang.reflect.Type type = new TypeToken<HashMap<String, String>>(){}.getType();
HashMap<String, String> testHashMap2 = gson.fromJson(storedHashMapString, type);
//use values
String toastString = testHashMap2.get("key1") + " | " + testHashMap2.get("key2");
Toast.makeText(this, toastString, Toast.LENGTH_LONG).show();
}
기본 설정에서지도를 저장하고 기본 설정에서지도를로드하는 간단한 코드를 작성했습니다. GSON 또는 Jackson 기능이 필요하지 않습니다. 방금 String을 키로 사용하고 Boolean을 값으로 사용하는 맵을 사용했습니다.
private void saveMap(Map<String,Boolean> inputMap){
SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
if (pSharedPref != null){
JSONObject jsonObject = new JSONObject(inputMap);
String jsonString = jsonObject.toString();
Editor editor = pSharedPref.edit();
editor.remove("My_map").commit();
editor.putString("My_map", jsonString);
editor.commit();
}
}
private Map<String,Boolean> loadMap(){
Map<String,Boolean> outputMap = new HashMap<String,Boolean>();
SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
try{
if (pSharedPref != null){
String jsonString = pSharedPref.getString("My_map", (new JSONObject()).toString());
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<String> keysItr = jsonObject.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Boolean value = (Boolean) jsonObject.get(key);
outputMap.put(key, value);
}
}
}catch(Exception e){
e.printStackTrace();
}
return outputMap;
}
Map<String, String> aMap = new HashMap<String, String>();
aMap.put("key1", "val1");
aMap.put("key2", "val2");
aMap.put("Key3", "val3");
SharedPreferences keyValues = getContext().getSharedPreferences("Your_Shared_Prefs"), Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();
for (String s : aMap.keySet()) {
keyValuesEditor.putString(s, aMap.get(s));
}
keyValuesEditor.commit();
Vinoj John Hosan의 답변에서 스핀 오프로 나는 같은 단일 키 대신 데이터의 키를 기반으로 더 일반적인 삽입을 허용하도록 답변을 수정했습니다 "My_map"
.
In my implementation, MyApp
is my Application
override class, and MyApp.getInstance()
acts to return the context
.
public static final String USERDATA = "MyVariables";
private static void saveMap(String key, Map<String,String> inputMap){
SharedPreferences pSharedPref = MyApp.getInstance().getSharedPreferences(USERDATA, Context.MODE_PRIVATE);
if (pSharedPref != null){
JSONObject jsonObject = new JSONObject(inputMap);
String jsonString = jsonObject.toString();
SharedPreferences.Editor editor = pSharedPref.edit();
editor.remove(key).commit();
editor.putString(key, jsonString);
editor.commit();
}
}
private static Map<String,String> loadMap(String key){
Map<String,String> outputMap = new HashMap<String,String>();
SharedPreferences pSharedPref = MyApp.getInstance().getSharedPreferences(USERDATA, Context.MODE_PRIVATE);
try{
if (pSharedPref != null){
String jsonString = pSharedPref.getString(key, (new JSONObject()).toString());
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<String> keysItr = jsonObject.keys();
while(keysItr.hasNext()) {
String k = keysItr.next();
String v = (String) jsonObject.get(k);
outputMap.put(k,v);
}
}
}catch(Exception e){
e.printStackTrace();
}
return outputMap;
}
You could try using JSON instead.
For saving
try {
HashMap<Integer, String> hash = new HashMap<>();
JSONArray arr = new JSONArray();
for(Integer index : hash.keySet()) {
JSONObject json = new JSONObject();
json.put("id", index);
json.put("name", hash.get(index));
arr.put(json);
}
getSharedPreferences(INSERT_YOUR_PREF).edit().putString("savedData", arr.toString()).apply();
} catch (JSONException exception) {
// Do something with exception
}
For getting
try {
String data = getSharedPreferences(INSERT_YOUR_PREF).getString("savedData");
HashMap<Integer, String> hash = new HashMap<>();
JSONArray arr = new JSONArray(data);
for(int i = 0; i < arr.length(); i++) {
JSONObject json = arr.getJSONObject(i);
hash.put(json.getInt("id"), json.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
String converted = new Gson().toJson(map);
SharedPreferences sharedPreferences = getSharedPreferences("sharepref",Context.MODE_PRIVATE);
sharedPreferences.edit().putString("yourkey",converted).commit();
Using PowerPreference.
Save Data
HashMap<String, Object> hashMap = new HashMap<String, Object>();
PowerPreference.getDefaultFile().put("key",hashMap);
Read Data
HashMap<String, Object> value = PowerPreference.getDefaultFile().getMap("key", HashMap.class, String.class, Object.class);
You can use this in a dedicated on shared prefs file (source: https://developer.android.com/reference/android/content/SharedPreferences.html):
getAll
added in API level 1 Map getAll () Retrieve all values from the preferences.
Note that you must not modify the collection returned by this method, or alter any of its contents. The consistency of your stored data is not guaranteed if you do.
Returns Map Returns a map containing a list of pairs key/value representing the preferences.
참고URL : https://stackoverflow.com/questions/7944601/how-to-save-hashmap-to-shared-preferences
'program story' 카테고리의 다른 글
목록에서 항목을 제거하는 지능적인 방법 (0) | 2020.09.23 |
---|---|
반전 된 인덱스와 일반 이전 인덱스의 차이점은 무엇입니까? (0) | 2020.09.23 |
Modernizr를 사용하여 IE를 감지하는 올바른 방법? (0) | 2020.09.23 |
HashMap Java 8 구현 (0) | 2020.09.23 |
Twitter Bootstrap 드롭 다운을위한 이벤트 핸들러? (0) | 2020.09.22 |