问题
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?
回答1:
From documentation of Parcel:
Parcel is not a general-purpose serialization mechanism. This class (and the corresponding Parcelable API for placing arbitrary objects into a Parcel) is designed as a high-performance IPC transport. As such, it is not appropriate to place any Parcel data in to persistent storage: changes in the underlying implementation of any of the data in the Parcel can render older data unreadable.
回答2:
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:
String json = location == null ? null : new Gson().toJson(location);
sharedPreferences.edit().putString("location", json).apply();
Retrieving a Location:
String json = sharedPreferences.getString("location", null);
return json == null ? null : new Gson().fromJson(json, Location.class);
来源:https://stackoverflow.com/questions/28439003/use-parcelable-to-store-item-as-sharedpreferences