在传递给下一个活动时,Parcelable中的Android问题

时间:2012-07-05 14:06:42

标签: android serialization parcelable

我正在尝试将自己的 消息类 从活动传递到另一个活动 因为我正在使用parcelable。 在尝试通过捆绑

活动1 - 传递捆绑

Intent i = new Intent(getApplicationContext(), Activity2.class);
Bundle b=new Bundle();
b.putParcelable("FolderList", mainMP3List)); //***mainMP3List is MusicFolder object***
i.putExtras(b);
startActivityForResult(i, 100); 

活动2 - 获取捆绑

if(b.containsKey("FolderList"))
mainMP3List = b.getParcelable("FolderList");//Error is the here (readBundle: bad magic number)

我无法从第二项活动中访问它们 我收到这样的错误

捆绑:readBundle:错误的幻数

import java.util.ArrayList;

import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;

public class MusicFolder implements Parcelable{

private ArrayList<SongsNameList> songsList=new ArrayList<SongsNameList>();  
private ArrayList<MusicFolder> listOfFolders=new ArrayList<MusicFolder>();


public ArrayList<SongsNameList> getSongsList() {
    return songsList;
}

public void addSongInList(SongsNameList song) {
    this.songsList.add(song);
}

public ArrayList<MusicFolder> getListOfFolders() {
    return listOfFolders;
}
public void addFolderInList(MusicFolder folder) {
    this.listOfFolders.add(folder);
}


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

@Override
public void writeToParcel(Parcel dest, int flags) {
    //dest.writeString(category);
    Bundle b = new Bundle();
    b.putParcelableArrayList("songs", songsList);
    b.putParcelableArrayList("folders", listOfFolders);
    dest.writeBundle(b);

}

public static final Parcelable.Creator<MusicFolder> CREATOR = 
        new Parcelable.Creator<MusicFolder>() { 
    public MusicFolder createFromParcel(Parcel in) { 
        MusicFolder category = new MusicFolder();
        //category.listOfFolders = in.readString();
        Bundle b1 = in.readBundle(SongsNameList.class.getClassLoader());        
        category.songsList = b1.getParcelableArrayList("songs");

        Bundle b2 = in.readBundle(MusicFolder.class.getClassLoader());        
        category.listOfFolders = b2.getParcelableArrayList("folders");

        return category;
    }

    @Override
    public MusicFolder[] newArray(int size) {
        return new MusicFolder[size];
    }
};



  }

2 个答案:

答案 0 :(得分:3)

没有测试过,但我认为不是:

    Bundle b1 = in.readBundle(SongsNameList.class.getClassLoader());        
    category.songsList = b1.getParcelableArrayList("songs");

    Bundle b2 = in.readBundle(MusicFolder.class.getClassLoader());        
    category.listOfFolders = b2.getParcelableArrayList("folders");

应该是这样的:

    Bundle b = in.readBundle(SongsNameList.class.getClassLoader());        
    category.songsList = b.getParcelableArrayList("songs");
    category.listOfFolders = b.getParcelableArrayList("folders");

答案 1 :(得分:0)

这可能是因为您按照特定顺序将值/类型写入Parcelable并以不同顺序读取它(其中一个数据边界被违反)。

检查您的保存/加载订单,如果您没有发现问题,请发布适用于Parcelable实施的代码,以供我们查看。