2013-01-08 7 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); 
    } 

} 

तब बनाते हैं तो आप इन धाराओं जब का उपयोग करना होगा serializing

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(); 
} 
संबंधित मुद्दे