简体   繁体   English

Android:将地图保存到SharedPreferences吗?

[英]Android: Save map to SharedPreferences?

I need to save data to SharedPreferences in such a way where I have an object like this: 我需要以这样的方式将数据保存到SharedPreferences中:

{
    "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 . 我知道您无法将地图保存到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. 我开始认为我最好的选择是使用ObjectOutputStream但是我不确定这是否是使用内部存储器的最好选择。 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 . 编辑:从Advice-Dog所说的话,我认为我最好的选择是使用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? 这是否意味着当我想(例如)向“天”的第二个索引添加另一个练习时,我将首先从首选项中获取对象,将其从gson转换为对象,然后添加练习,然后将其转换回到gson ,然后覆盖首选项? I am not saying this is bad I just want to know if this is what should be done and if it is advisable. 我并不是说这很不好,我只是想知道这是应该做的,还是可取的。

When saving more complex types in Android, I would suggest using gson . 在Android中保存更复杂的类型时,建议使用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. Gson是Google的JSON解析库,即使您不使用JSON,也可以将Objects转换为JSON String,并轻松存储它。

For example, you can convert your list of Objects into a String like this. 例如,您可以像这样将Objects列表转换为String

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)

Using JSON is the best solution but here is another solution (just to add another way to solve a problem): 使用JSON是最好的解决方案,但这是另一种解决方案(只是添加另一种解决问题的方法):

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 但是要找到空的日期或空的运动编号,您必须获取共享首选项的所有键并使用正则表达式或循环

you can use library for google ==> Gson add this in dependencies in gradle 您可以将库用于google ==> Gson在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 您可以将此库将对象作为String转换为json,然后可以将其保存在共享的Pref As String中,当从Pref获取字符串时,可以将String转换为对象

convert json to model 将json转换为模型

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

convert model to json as String 将模型转换为JSON作为字符串

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

must model the same hierarchy for json where make problem during converting 必须为json建模相同的层次结构,在转换过程中会出现问题

Model for you json must be like this model json的模型必须类似于此模型

  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;
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM