In my Android app I am already saving some strings to the SharedPreferences and serializing an ArrayList with Strings so this data is saved and can be used for future purposes. Even when the app is closed.
A minute ago I discovered that I need to save my PolylineOptions for future use as well. PolylineOptions contain some coordinates to draw a line on my map with a color and width.
I discovered that PolylineOptions aren't serializeable like Strings. Is there a way to 'save' my PolylineOptions or do I need to save the settings of the PolylineOptions and create the PolylineOptions on startup?
So the real question is. How do I serialize a non serializeable object?
One option is to create a serializable version of the PolylineOptions class.
For example:
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;
}
}
If the PolylineOptions object is not final, you can extend it with a Serializable class (a simple wrapper) and implement the
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void readObjectNoData()
throws ObjectStreamException;
methods in the derived class.
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;
}
}