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:
public class Location implements Parcelable{ private double latitude, longitude; private int sensors = 1; private boolean day; private int cloudiness; /* Måste ha samma ordning som writeToParcel för att kunna återskapa objektet. */ public Location(Parcel in){ this.latitude = in.readDouble(); this.longitude = in.readDouble(); this.sensors = in.readInt(); } public Location(double latitude, double longitude){ super(); this.latitude = latitude; this.longitude = longitude; } public void addSensors(){ sensors++; } public void addSensors(int i){ sensors = sensors + i; } + Some getters and setters.
Now I am in need of storing these objects more permanently. I read somewhere that I can serialize the objects and save as sharedPreferences. Do I have to implement serializeable aswell or can I do something similar with parcelable?
We can store fields of any Object to shared preference by serializing the object to String.
You can save String and custom array list using Gson library. =>First you need to create function to save array list to SharedPreferences. public void saveListInLocal(ArrayList<String> list, String key) { SharedPreferences prefs = getSharedPreferences("AppName", Context. MODE_PRIVATE); SharedPreferences.
Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With