how to serialize for android.location class?

别等时光非礼了梦想. 提交于 2019-12-23 09:34:13

问题


I'm trying to serialize my location class (using android.location class)

but, it gives me an error!

11-21 21:25:37.337: W/System.err(3152): java.io.NotSerializableException: android.location

So, I tried to extend the android.location.Location class.

private class NewLocation extends Location implements Serializable {
        private String Provider;
        private double Latitude, Longitude, Altitude;

private float bear;
        public NewLocation(Location l) {
            super(l);
            Provider = l.getProvider();
            Latitude = l.getLatitude();
            Longitude = l.getLongitude();
            Altitude = l.getAltitude();
            bear = l.getBearing();
        }
    }

After that, i tried to serialize the extended class, but the same error.

Here is the serialization code

 public static byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        ObjectOutput oos = new ObjectOutputStream(bao);
        byte[] data = null;
        oos.writeObject(obj);
        oos.flush();
        oos.close();
        data = bao.toByteArray();
        return data;
    }

why this error?


回答1:


Android's Location class already implements Parcelable. So you are better off with it rather than implementing your own Serialization.

Simply use the following to get bytes out from Location:

Parcel p = Parcel.obtain();
objLocation.writeToParcel(p, 0);
final byte[] b = p.marshall();      //now you've got bytes
p.recycle();

However, you should not save bytes (in persistent storage) from Parecelable object for later use because it is designed for high-performance IPC transport, and is not a general-purpose serialization mechanism.




回答2:


You can not make a non-serializable class serializable just implementing the Serializable interface. A serializable class must inherit from a serializable class (if an inherited class) and have all its attributes serializable themselves.

All subtypes of a serializable class are themselves serializable. http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

However, if you want to serialize a Parcelable class it is still possible, but surely it would not be a good practice.



来源:https://stackoverflow.com/questions/20121159/how-to-serialize-for-android-location-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!