javaserializationsharedpreferencespolylineandroid-maps-v2

Serialize or save PolylineOptions in Android


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?


Solution

  • 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.