Use parcelable to store item as sharedpreferences?

可紊 提交于 2019-12-09 05:04:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!