Makarele
Makarele

Reputation: 59

Trouble with displaying hashmap

My App: has two activities, one to create two strings (name and message), which are saved into a hashmap, transferred into JSON and saved in a SharedPreference. The other activity fetches this SharedPreference, transfers it into a hashmap again. Then the map is "read out" by an Iterator.

Supposed to be: My Idea is, that if I do this process several times, the iterator "reads out" all the entries to the hashmap.

Problem: However, only the last input gets displayed.

Question: Why is only the last input displayed? Am I overriding the hashmap or parts of it? And if so, how can I avoid it? Or what else am I doing wrong?


Activity 1:

LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
    map.put(message, name);

    Gson gson = new Gson();
    String hashMapString = gson.toJson(map);

    SharedPreferences prefs = getSharedPreferences("SP", MODE_PRIVATE);
    prefs.edit().putString("hashString", hashMapString).apply();

Activity 2:

Gson gson = new Gson();
        SharedPreferences prefs = getSharedPreferences("SP", MODE_PRIVATE);

        String storedHashMapString = prefs.getString("hashString", "Error");
        java.lang.reflect.Type type = new TypeToken<LinkedHashMap<String, String>>(){}.getType();
        LinkedHashMap<String, String> map = gson.fromJson(storedHashMapString, type);


    Iterator myIterator = map.keySet().iterator();
    while(myIterator.hasNext()) {
        String key=(String)myIterator.next();
        String value=(String)map.get(key);
        Toast.makeText(getApplicationContext(), "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
    }

Upvotes: 0

Views: 65

Answers (2)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

while doing this

prefs.edit().putString("hashString", hashMapString).apply();

you are just saving values of newly created hashmap but old losing values which were saved previously using hashString key

Solution: fetch the old value and save it along with new values

Option one : fetch previous string , convert it to jsonobject then add the values to map

Reference : creating Hashmap from a JSON String

Option two : if you have only string key-value pair then

  • remove { and } from both new and old map strings then simply combine them and add { and } boundary symbols

     String allValues ="{"+((prefs.getString("hashString", "")+hashMapString)
                                      .replace("{","").replace("}",""))+"}";
    

then later save it

prefs.edit().putString("hashString", allValues).apply();

Upvotes: 2

Nick
Nick

Reputation: 595

you are seeing the last input because putString overwrites whatever was there in the first place

https://developer.android.com/reference/android/content/SharedPreferences.Editor.html

Upvotes: 0

Related Questions