Home > Software design >  Storing MutableMap on SharedPreferences and retrieving it
Storing MutableMap on SharedPreferences and retrieving it

Time:08-30

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:

 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!

CodePudding user response:

"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.

  • Related