Android serializable problem

前端 未结 6 696
眼角桃花
眼角桃花 2021-01-04 19:07

I created a class, which has several member variables, all of which are serializable... except one Bitmap! I tried to extend bitmap and implement serializable, not thinking

6条回答
  •  感情败类
    2021-01-04 19:27

    If it is OK to save the bitmap data separately in your application, you can do the following:

    In your class that saves the current state, save the bitmap to a folder of your choice:

    FileOutputStream out = new FileOutputStream();
    bitmap.compress(CompressFormat.PNG, 100, out);
    

    In the class that has the bitmap as member, have the path as the serializable member and reconstruct the bitmap after deserialization:

    public class MyClass implements Serializable
    {
        // ...
        private String bitmapPath;
        transient Bitmap bitmap;
        // ...
    
        private void writeObject(ObjectOutputStream out) throws IOException
        {
            out.defaultWriteObject();
        }
    
        private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
        {
            in.defaultReadObject();
            bitmap = BitmapFactory.decodeFile(path);
        }
    

    You can implement any other build-up functionality in the readObject() function if needed, since the object is fully constructed after the defaultReadObject() call.

    Hope this helps.

    BTW, http://developer.android.com/reference/android/os/Parcel.html recommends against using Parcelable for serialization purposes. I do not have enough points yet to leave a comment, so I am editing my own answer to put in this remark.

提交回复
热议问题