1

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?

4

2 回答 2

0

一种选择是创建 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 对象不是最终的,您可以使用 Serializable 类(一个简单的包装器)对其进行扩展并实现

 private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;
 private void readObjectNoData() 
     throws ObjectStreamException;
 

派生类中的方法。

于 2013-03-19T17:06:03.733 回答
0
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;

  }

}
于 2019-03-27T04:13:00.503 回答