Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Storing MutableMap on SharedPreferences and retrieving it

I was trying to store a MutableMap in shared preferences so I could retrieve it later, but my app is crashing when retrieving and casting the mutableMap.

First I initialized the map and filled it with values

val mapYearMonths: MutableMap<Int, Map<Int, Map<Int, Map<Map<String, Int>, Int>>>> =
                HashMap<Int, Map<Int, Map<Int, Map<Map<String, Int>, Int>>>>()

Then I stored it, which seems to work correctly:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 val stepsRecord: String = Gson().toJson(mapYearMonths)
        val editor = sharedPreferences.edit();
        editor.putString("stepsRecord", stepsRecord);
        editor.commit();

And finally I retrieved it, which crashes at line 3

val mapYearMonthsString: String = sharedPreferences.getString("stepsRecord", "0")!!
        val mapYearMonthsAny: MutableMap<*, *>? =
            Gson().fromJson(mapYearMonthsString, MutableMap::class.java)
        return mapYearMonthsAny as MutableMap<Int, Map<Int, Map<Int, Map<Map<String, Int>, Int>>>>

This is the error I get:

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.walker/com.example.walker.MainActivity}: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 2 path $
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3308)

Any clue on what I could be doing wrong? I tried looking up but couldn’t find anything on this. What am I doing something wrong? Should I use another method to store the data? Thanks everyone for the help in advance!

>Solution :

"0" is not a JSON object and cannot be parsed as a MutableMap. Use a default value that can be parsed as a MutableMap, such as "{}" for an empty map.

Should I use another method to store the data?

Possibly, but we do not know how you are using this data, how big this Map is, why you chose SharedPreferences in the first place, etc.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading