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)
| 归档时间: |
|
| 查看次数: |
18076 次 |
| 最近记录: |