Thursday, 3 January 2019

Android: Save map to SharedPreferences?

I need to save data to SharedPreferences in such a way where I have an object like this:

{
    "days": [
        {
            "exercises": [
                {
                    "name": "Bench Press",
                    "sets": 3,
                    "reps": 8
                },
                {
                    "name": "Skull Crushers",
                    "sets": 3,
                    "reps": 8
                },
                {
                    "name": "Flys",
                    "sets": 3,
                    "reps": 8
                }
            ]
        },
        {
            "exercises": [
                {
                    "name": "Bench Press",
                    "sets": 3,
                    "reps": 8
                },
                {
                    "name": "Skull Crushers",
                    "sets": 3,
                    "reps": 8
                },
                {
                    "name": "Flys",
                    "sets": 3,
                    "reps": 8
                }
            ]
        }
    ]
}

I will need to pull from the object and add to the object. I know that you can't save maps to SharedPreferences. I am starting to think that my best bet is to use ObjectOutputStream but I am not sure if that is the best bet to use internal memory. I guess I am just looking for guidance as to what my best options are.

edit: from what Advice-Dog said, I am thinking my best bet is to use gson. So does that mean that when I want to (for example) add another exercise to the second index of "days" that I will first grab the object from preferences, convert it from gson to an object, then add the exercise, then convert it back to gson, then overwrite the preferences? I am not saying this is bad I just want to know if this is what should be done and if it is advisable.



from Android: Save map to SharedPreferences?

No comments:

Post a Comment