Java 在Android中序列化或保存多段线选项
在我的Android应用程序中,我已经将一些字符串保存到SharedReferences中,并使用字符串序列化ArrayList,以便保存这些数据并用于将来的用途。即使应用程序已关闭。 一分钟前,我发现我还需要保存我的多段线选项以备将来使用。多段线选项包含一些坐标,用于在地图上绘制具有颜色和宽度的线 我发现PolylineOptions不像字符串那样可序列化。有没有办法“保存”我的多段线选项,或者我需要保存多段线选项的设置并在启动时创建多段线选项Java 在Android中序列化或保存多段线选项,java,serialization,sharedpreferences,polyline,android-maps-v2,Java,Serialization,Sharedpreferences,Polyline,Android Maps V2,在我的Android应用程序中,我已经将一些字符串保存到SharedReferences中,并使用字符串序列化ArrayList,以便保存这些数据并用于将来的用途。即使应用程序已关闭。 一分钟前,我发现我还需要保存我的多段线选项以备将来使用。多段线选项包含一些坐标,用于在地图上绘制具有颜色和宽度的线 我发现PolylineOptions不像字符串那样可序列化。有没有办法“保存”我的多段线选项,或者我需要保存多段线选项的设置并在启动时创建多段线选项 所以真正的问题是。如何序列化不可序列化的对象?一
所以真正的问题是。如何序列化不可序列化的对象?一个选项是创建PolylineOptions类的可序列化版本 例如:
public class Blammy implements Serializable
{
public Blammy(final PolylineOptions polylineOptions)
{
//retrieve all values and store in Blammy class members.
}
public PolylineOptions generatePolylineOptions()
{
PolylineOptions returnValue = new PolylineOptions();
// set all polyline options values.
return returnValue;
}
}
如果PolylineOptions对象不是final,则可以使用可序列化类(简单包装器)对其进行扩展,并实现
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void readObjectNoData()
throws ObjectStreamException;
派生类中的方法。公共类polyLineData实现可序列化{
public class polyLineData implements Serializable {
PolylineOptions polylineOptions;
public polyLineData(){;}
public polyLineData(PolylineOptions polylineOptions) {
this.polylineOptions = polylineOptions;
}
public static void writeData(Context c, polyLineData pd)
{
Gson gson=new Gson();
SharedPreferences.Editor spEditor=c.getSharedPreferences("RecordedPoints",MODE_PRIVATE).edit();
String uniqueID = UUID.randomUUID().toString();
spEditor.putString(uniqueID,gson.toJson(pd)).apply();
}
public static ArrayList<PolylineOptions> getData(Context c)
{
Gson gson=new Gson();
ArrayList<PolylineOptions> data=new ArrayList<>();
SharedPreferences sp=c.getSharedPreferences("RecordedPoints",MODE_PRIVATE);
Map<String,?> mp=sp.getAll();
for(Map.Entry<String,?> entry : mp.entrySet()){
String json=entry.getValue().toString();
polyLineData pd=gson.fromJson(json,polyLineData.class);
data.add(pd.polylineOptions);
}
return data;
}
}
多段线选项多段线选项;
公共多段线数据(){;}
公共多段线数据(多段线选项多段线选项){
this.polylineOptions=polylineOptions;
}
公共静态void writeData(上下文c、多段线数据pd)
{
Gson Gson=新的Gson();
SharedReferences.Editor spEditor=c.getSharedReferences(“RecordedPoints”,MODE_PRIVATE).edit();
字符串uniqueID=UUID.randomUUID().toString();
putString(uniqueID,gson.toJson(pd)).apply();
}
公共静态ArrayList getData(上下文c)
{
Gson Gson=新的Gson();
ArrayList数据=新的ArrayList();
SharedReferences sp=c.getSharedReferences(“RecordedPoints”,MODE_PRIVATE);
Map mp=sp.getAll();
对于(Map.Entry:mp.entrySet()){
字符串json=entry.getValue().toString();
polyLineData pd=gson.fromJson(json,polyLineData.class);
添加数据(pd.多段线选项);
}
返回数据;
}
}