2015-02-10 203 views
11

我有一些对象,位置,在我的应用程序存储在一个ArrayList中,并使用parcelable来移动这些活动之间。该对象的代码如下所示:使用parcelable将项目存储为sharedpreferences?

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. 

现在我需要更长期地存储这些对象。我读了一些可以序列化对象并保存为sharedPreferences的地方。我是否必须实现可序列化,或者我可以使用与parcelable类似的方法吗?

回答

22

documentation of Parcel

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

+0

啊!在这种情况下,我想我只需要序列化它。 – xsiand 2015-02-10 18:34:11

+0

@xsiand相关:http://stackoverflow.com/questions/5418160/store-and-retrieve-a-class-object-in-shared-preference – Micro 2016-03-06 23:55:38

23

由于parcelable不利于把你的数据持久性存储(见StenSoft的答案),你可以使用GSON坚持自己的位置,而不是:

保存地点:

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

检索地点:

String json = sharedPreferences.getString("location", null); 
return json == null ? null : new Gson().fromJson(json, Location.class); 
相关问题