Use parcelable to store item as sharedpreferences?

前端 未结 3 1077
谎友^
谎友^ 2021-02-05 04:26

I have a couple objects, Location, in my app stored in an ArrayList and use parcelable to move these between activities. The code for the object looks like this:



        
3条回答
  •  忘掉有多难
    2021-02-05 04:51

    Since parcelable doesn't help to place your data in persistent storage (see StenSoft's answer), you can use gson to persist your Location instead:

    Saving a Location:

    val json = Gson().toJson(location)
    sharedPreferences.edit().putString("location", json).apply()
    

    Retrieving a Location:

    val json = sharedPreferences.getString("location", null)
    return Gson().fromJson(json, Location::class.java)
    

    In case you're still using Java, replace val with String, Gson() with new Gson(), ::class.java with .class and end each line with a semicolumn.

提交回复
热议问题