Search code examples
javaandroidsharedpreferences

Save hashmap in SharedPreferences


I need to save this hashmap in SharedPreferences i tried to convert it into Json but it didn't work

 Map<String, String> userMap = new HashMap<String , String>() {{
                for(int i = 0; i < userList.size(); i++ ) {
                    String id= userList.get(i).getId();
                    String name = userList.get(i).getName();
                    put(id, name);

                }
            }};
            Gson gson = new Gson();
            String jsonString = gson.toJson(userMap);
            SessionManager sessionManager=new SessionManager(LoginActivity.this);
            sessionManager.saveMap(jsonString); 

jsonString is returing null even usermap has data I really need this to advance in my work appreciate anyhelp.


Solution

  • Gson is not recognizing the anonymous class that results from doing it that way.

    Try initializing the map without using the {{}} construct. e.g.

    Map<String, String> userMap = new HashMap<String , String>();
    
    for(int i = 0; i < userList.size(); i++ ) {
        String id= userList.get(i).getId();
        String name = userList.get(i).getName();
        put(id, name);
    }
    
    Gson gson = new Gson();
    String jsonString = gson.toJson(userMap);
    SessionManager sessionManager=new SessionManager(LoginActivity.this);
    sessionManager.saveMap(jsonString); 
    

    To convert this json back to a Map<String, String> you can use TypeToken as suggested here.

    Gson gson = new Gson();
    Type type = new TypeToken<Map<String, String>>() {}.getType();
    Map<String, String> nameEmployeeMap = gson.fromJson(jsonString, type);