使用parcelable将项目存储为共享首选项?

xsi*_*and 21 java storage android serializable

我有一些对象,位置,在我的应用程序中存储在ArrayList中,并使用parcelable在活动之间移动它们.该对象的代码如下所示:

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.
Run Code Online (Sandbox Code Playgroud)

现在我需要更永久地存储这些对象.我在某处读到了我可以序列化对象并另存为sharedPreferences.我是否必须实现序列化,或者我可以使用parcelable做类似的事情吗?

Cri*_*tan 56

由于parcelable无法将数据放在持久存储中(请参阅StenSoft的回答),因此您可以使用gson来保留您的位置:

保存位置:

String json = location == null ? null : new Gson().toJson(location);
sharedPreferences.edit().putString("location", json).apply();
Run Code Online (Sandbox Code Playgroud)

检索位置:

String json = sharedPreferences.getString("location", null);
return json == null ? null : new Gson().fromJson(json, Location.class);
Run Code Online (Sandbox Code Playgroud)


Ste*_*oft 28

包裹的文件:

包裹不是通用序列化机制.此类(以及用于将任意对象放入包中的相应Parcelable API)被设计为高性能IPC传输.因此,将任何Parcel数据放入持久存储中是不合适的:Parcel中任何数据的底层实现的更改都可能导致旧数据不可读.