2013-01-08 8 views
10

v2 Google PlayサービスのGoogle's LatLng classを使用しています。その特定のクラスは最終的なもので、java.io.Serializableを実装していません。 LatLngクラスを実装する方法はありますかSerializable第三者非シリアル化可能な最終クラス(GoogleのLatLngクラスなど)をシリアル化する方法はありますか?

public class MyDummyClass implements java.io.Serializable { 
    private com.google.android.gms.maps.model.LatLng mLocation; 

    // ... 
} 

私はmLocation過渡を宣言する必要はありません。

+0

回避方法を探します – UDPLover

答えて

25

Serializableではなく、Parcelableです(代わりにオプションになる場合)。そうでない場合は、自分でシリアル化を処理することができます:

public class MyDummyClass implements java.io.Serialiazable { 
    // mark it transient so defaultReadObject()/defaultWriteObject() ignore it 
    private transient com.google.android.gms.maps.model.LatLng mLocation; 

    // ... 

    private void writeObject(ObjectOutputStream out) throws IOException { 
     out.defaultWriteObject(); 
     out.writeDouble(mLocation.latitude); 
     out.writeDouble(mLocation.longitude); 
    } 

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 
     in.defaultReadObject(); 
     mLocation = new LatLng(in.readDouble(), in.readDouble()); 
    } 
} 
+0

ありがとうございました。それは私のために働いた。 –

2

ObjectOutputStreamをご覧ください。

まず、あなたはドロップインあなたのオブジェクトの代替を作成する必要があります:

public class SerializableLatLng implements Serializable { 

    //use whatever you need from LatLng 

    public SerializableLatLng(LatLng latLng) { 
     //construct your object from base class 
    } 

    //this is where the translation happens 
    private Object readResolve() throws ObjectStreamException { 
     return new LatLng(...); 
    } 

} 

次に次にあなたがする場合、これらのストリームを使用する必要があります適切なObjectOutputSTream

public class SerializableLatLngOutputStream extends ObjectOutputStream { 

    public SerializableLatLngOutputStream(OutputStream out) throws IOException { 
     super(out); 
     enableReplaceObject(true); 
    } 

    protected SerializableLatLngOutputStream() throws IOException, SecurityException { 
     super(); 
     enableReplaceObject(true); 
    } 

    @Override 
    protected Object replaceObject(Object obj) throws IOException { 
     if (obj instanceof LatLng) { 
      return new SerializableLatLng((LatLng) obj); 
     } else return super.replaceObject(obj); 
    } 

} 

を作成シリアライズ

private static byte[] serialize(Object o) throws Exception { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ObjectOutputStream oos = new SerializableLatLngOutputStream(baos); 
    oos.writeObject(o); 
    oos.flush(); 
    oos.close(); 
    return baos.toByteArray(); 
} 
関連する問題