包裹列表<>内置Bitmaps的自定义对象

时间:2014-07-30 11:09:41

标签: android arraylist bitmap parcelable

我需要从一个Activity转到另一个新闻列表(它是一个RSS阅读器),以便在ViewPager中显示它们。

有关新闻的所有数据都存储在一个类中:

public class SingleNew implements java.io.Serializable{

    public String title;
    public String link;
    public Date date;
    public Bitmap image;

}

因此,在第一个活动中,我已经下载了包含图像的所有新闻,为了避免在其他活动中再次下载,我决定将它们作为可分配对象传递给Intent。所以我创建了MyCustomParcelable。

public class CustomParcelable implements Parcelable {

    public List<SingleNew> news;

    public CustomParcelable(){
        news= new ArrayList<SingleNew>();
    }

    public CustomParcelable(Parcel in) {
        news= new ArrayList<SingleNew>();
        readFromParcel(in);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
         dest.writeList(news);
    }

    private void readFromParcel(Parcel in) {
        news = new ArrayList<SingleNew>();
        in.readList(news, List.class.getClassLoader());
    }

    public static final Parcelable.Creator CREATE = new Parcelable.Creator() {

         public CustomParcelable createFromParcel(Parcel parcel) {
              return new CustomParcelable(parcel);
         }

         public CustomParcelable[] newArray(int size) {
              return new CustomParcelable[size];
         }


    };
}

当我执行startActivity()时,我的控制台会抛出此消息,因为Bitmaps需要特殊处理。

Caused by: java.io.NotSerializableException: android.graphics.Bitmap

我知道如何将单个位图作为我CustomParcelable对象的一个​​属性传递,但在这种情况下,我有一个List<SingleNew>,每个位图内部都有Bitmap,所以我不知道知道如何准备。

我找到了关于位图的其他问题,但正如我所说,解释如何作为单个属性传递,而不是作为我的自定义对象列表的属性。

此外,我会问这是否是传递大量图像的最佳方式。我在其他问题中读到,更多的是将它们存储在内部存储中,然后恢复。这是真的吗?或者这种方式是正确的?

1 个答案:

答案 0 :(得分:3)

使用byte[]代替Bitmap

使用这些函数在对象之间进行转换

 public static byte[] convert(Bitmap bitmap) throws IOException {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);
    byte[] array = stream.toByteArray();
    stream.close();
    return array;


}
public static Bitmap convert(byte[] array) {
    return BitmapFactory.decodeByteArray(array,0,array.length);
} 
相关问题