包裹一个列表<>包含位图的自定义对象



我需要从一个活动向另一个活动传递一个新闻列表(它是一个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()时,我的控制台会抛出此消息,因为位图需要特殊处理。

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

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

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

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

使用位图的byte[]安装

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

 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);
} 

最新更新