Slaknation
Slaknation

Reputation: 1926

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.

Upvotes: 4

Views: 4841

Answers (3)

yousef
yousef

Reputation: 1363

you can use library for google ==> Gson add this in dependencies in gradle

 implementation 'com.google.code.gson:gson:2.8.0' 

you can this library convert object to json as String then you can save it in shared Pref As String when you get it String from Pref you can convert String to object

convert json to model

    /*type of model*/=new Gson().fromJson(/*json string*/,/*type of model*/)

convert model to json as String

 new Gson().toJson(/*model you want to convert */)===> return String

must model the same hierarchy for json where make problem during converting

Model for you json must be like this model

  public class JSONModel implements Serializable {


    @SerializedName("days")
    private List<Day> mDays;

    public List<Day> getDays() {
        return mDays;
    }

    public void setDays(List<Day> days) {
        mDays = days;
    }

    public class Day {

        @SerializedName("exercises")
        private List<Exercise> mExercises;

        public List<Exercise> getExercises() {
            return mExercises;
        }

        public void setExercises(List<Exercise> exercises) {
            mExercises = exercises;
        }

    }
    public class Exercise {

        @SerializedName("name")
        private String mName;
        @SerializedName("reps")
        private Long mReps;
        @SerializedName("sets")
        private Long mSets;

        public String getName() {
            return mName;
        }

        public void setName(String name) {
            mName = name;
        }

        public Long getReps() {
            return mReps;
        }

        public void setReps(Long reps) {
            mReps = reps;
        }

        public Long getSets() {
            return mSets;
        }

        public void setSets(Long sets) {
            mSets = sets;
        }

    }

}

Upvotes: 1

Amani
Amani

Reputation: 3977

Using JSON is the best solution but here is another solution (just to add another way to solve a problem):

you can use shared preferences keys like this:

for((dayIndex, day) in days.withIndex)
    for((exeIndex, exe) in day)
       for((key, value) in exe)
          addExercise(day = dayIndex, exercise = exeIndex, key = key, value = value)


fun addExercise(day: String, exercise: String, key: String, value: String) = 
     preferences.putString("day${day}_exe${exercise}_${key}", value).apply()           

then you can get first exercise name from second day like this:

val first_exercise_second_day = preferences.getString("day2_exe1_name")

and you can add a exercise to third day like this:

 addExercise(day = "3", exercise = "1", key = "name", value = "Flys")
 addExercise(day = "3", exercise = "1", key = "sets", value = "5")
 addExercise(day = "3", exercise = "1", key = "reps", value = "3")

But to find empty day or empty exercise number you have to get all keys of shared preference and use regular expression or loops

Upvotes: 1

advice
advice

Reputation: 5988

When saving more complex types in Android, I would suggest using gson. Gson is Google's JSON parsing library, and even if you're not using JSON, you can convert your Objects into a JSON String, and store that easily.

For example, you can convert your list of Objects into a String like this.

val list : List<MyObject>  // ... add items to your list

// Convert to JSON

val string = gson.toJson(list)

// Store it into Shared Preferences
preferences.putString("list", string).apply()

And then you can easily get it back into a list like this.

// Fetch the JSON 

val string = preferences.getString("list", "")

// Convert it back into a List

val list: List<MyObject> = gson.fromJson(string, object : TypeToken<List<MyObject>>() {}.type)

Upvotes: 8

Related Questions