Android: Any shortcut to Serializable from Parcelable without using marshall()?
Asked Answered
V

1

7

I'm aware of the performance differences between Parcelable (fast) and Serializable (slow). However, I need to store certain application information persistently, not just within one lifecycle, thus onSaveInstanceState and associated methods utilising Parcelable objects aren't appropriate.

So I turned my attention to Serializable. Primarily I have AbstractList types to store - which is fine, since they implement Serializable. However, many of the types I store inside these are Parcelable but not Serializable, e.g. RectF.

I thought "no problem", since I can easily generate a Parcel via Parcelable.writeToParcel(parcel, flags) then call marshall() on it to create a byte[] which I can serialize and deserialize. I figured I'd use generics; create a SerializableParcelable<Parcelable> implements Serializable class, allowing a one-fit solution for all Parcelable types I wish to serialize. Then I would e.g. store each RectF inside this wrapper within ArrayList, and lo-and-behold the list and its Parcelable contents are serializable.

However, the API docs state that marshall() mustn't be used for persistent storage:

public final byte[] marshall ()

Returns the raw bytes of the parcel.

The data you retrieve here must not be placed in any kind of persistent storage (on local disk, across a network, etc). For that, you should use standard serialization or another kind of general serialization mechanism. The Parcel marshalled representation is highly optimized for local IPC, and as such does not attempt to maintain compatibility with data created in different versions of the platform.

So now I'm stuck. I can either ignore this warning and follow the route I've outlined above, or else circumvent the issue by extending each individual Parcelable I want to serialize and creating bespoke serialization methods, which seems extremely wasteful of time and effort.

Does anyone know of a 'correct' shortcut to serialize a Parcelable object without using marshall()? Or should I plough on without heeding the warning specified? Perhaps an SQLite database is the way to go, but I'm unsure and would like your advice.

Many thanks.

Violate answered 5/5, 2011 at 11:6 Comment(3)
Is there some reason why you can't used SharedPreferences to store the persistant data? Oh, wait, the answer to that is obvious, sorry!Caterpillar
SharedPreferences only offers methods for persistent storage of simple types like int, String etc. There is no functionality for storing a Parcelable, Serializable or byte[].Violate
Yeah, I just realised that. /o\Caterpillar
E
-2

For any object you need to serialize you can use objectOutPutStream .By using this you can write objects into the file system of the device.So this can used to save Parcelable objects also.

Below is the code to save object to File System.

    public static void witeObjectToFile(Context context, Object object, String        filename) {

    ObjectOutputStream objectOut = null;
    FileOutputStream fileOut = null;
    try {
        File file = new File(filename);
        if(!file.exists()){
            file.createNewFile();
        }
        fileOut = new FileOutputStream(file,false);
        objectOut = new ObjectOutputStream(fileOut);
        objectOut.writeObject(object);
        fileOut.getFD().sync();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }finally {
        if (objectOut != null) {
            try {
                objectOut.close();
            } catch (IOException e) {
                // do nowt
            }
        }
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (IOException e) {
                // do nowt
            }
        }
    }
}`

Inorder to read the Object use ObjectInputStream . Find the below code.

    public static Object readObjectFromFile(Context context, String filename) {

    ObjectInputStream objectIn = null;
    Object object = null;
    FileInputStream fileIn = null;
    try {
        File file = new File(filename);
        fileIn = new FileInputStream(file);//context.getApplicationContext().openFileInput(filename);
        objectIn = new ObjectInputStream(fileIn);
        object = objectIn.readObject();

    } catch (FileNotFoundException e) {
        // Do nothing
    }catch (NullPointerException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }finally {
        if (objectIn != null) {
            try {
                objectIn.close();
            } catch (IOException e) {
                // do nowt
            }
        }
        if(fileIn != null){
            try {
                fileIn.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    return object;
}`

Regards,
Sha

Emmeram answered 29/3, 2012 at 10:11 Comment(1)
Sha you're missing the point that ObjectOutputStream.writeObject(object) will throw non Serializable error if the object is not declared Serilizable. This is the whole root of the problems that @KomodoDaveis describes. Parcelables are not necessarily Serializable. I am struggliing with the same issue too trying to persist Intent objects that have Bundles.Greeley

© 2022 - 2024 — McMap. All rights reserved.