Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use parcelable to store item as sharedpreferences?

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?

like image 447
xsiand Avatar asked Feb 10 '15 18:02

xsiand


People also ask

Can we store objects in SharedPreferences?

We can store fields of any Object to shared preference by serializing the object to String.

Can I save array list in SharedPreferences?

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.

How do I save something in 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.


1 Answers

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.

like image 51
Cristan Avatar answered Sep 21 '22 05:09

Cristan