2016-08-29 2 views

Antwort

1

Sie können converti HashMap als Json mit Gson Bibliothek und legen Sie sich als String speichern und erhalten. So etwas wie das:

2

Der einfachste Weg wäre, Googles Gson zu verwenden, um die HashMap als json zu speichern. Erstellen Sie eine Wrapper-Klasse für Ihre HashMap mit den Getter- und Setter-Methoden. Siehe die folgende Antwort.

https://stackoverflow.com/a/11931812/5425930

2

auf Bohnen Stellen (oder pojo) Klasse die Hashmap zu speichern.

public class HashListBean{ 
    private HashMap<String, List<String>> mChildMap; 
    //create constructer with hashMap as argument 
    public HashListBean(HashMap<String, List<String>> mChildMap){ 
     this.mChildMap=mChildMap; 
    } 
    public HashMap<String, List<String>> getHashMap(){ 
    return mChildMap; 
    } 
} 

Funktion HashMap in SharedPreference

private void insertToSP(HashMap<String, List<String>> jsonMap) { 
     HashListBean hashListBean= new HashListBean(jsonMap); 
     String jsonString = new Gson().toJson(hashListBean); 
     SharedPreferences sharedPreferences = getSharedPreferences("HashMap", MODE_PRIVATE); 
     SharedPreferences.Editor editor = sharedPreferences.edit(); 
     editor.putString("map", jsonString); 
     editor.apply(); 
    } 

Funktion zum Einfügen Hashmap von SharedPreference

private HashMap<String, List<String>> readFromSP(){ 
     SharedPreferences sharedPreferences = getSharedPreferences("HashMap", MODE_PRIVATE); 
     String defValue = new Gson().toJson(new HashListBean(new HashMap<String, List<String>>())); 
     String json=sharedPreferences.getString("map",defValue); 
     HashListBean hashListBean=new Gson().fromJson(json,HashListBean.class); 
     return hashListBean.getHashMap(); 
    } 

Dieses dependancy in gradle

compile 'com.google.code.gson:gson:2.6.2' 
lesen