如何通过Bundle of Activity传递Parcelable,一个List类型的对象? 不断产生错误类型NPE,在OnCreateView中准备Parcelable。
// Fragment object в Activity
public Fragment systemFragList(){
a = new AppsManagerFragment();
b = new Bundle();
dApps = new DataApps(this);
//transmission through List the designer
listCreater = new MakingListObject(dApps.getSystemAppsList());
b.putParcelable("List", listCreater); // transfer Parcelable object through Bundle
a.setArguments(b);
return a;
};
// Parcelable class
public class MakingListObject implements Parcelable {
private List<ApplicationInfo> list;
// get an object List <ApplicationInfo> constructor
public MakingListObject(List<ApplicationInfo> l) {
this.list = l;
}
public MakingListObject(Parcel in) {
in.readTypedList(list, ApplicationInfo.CREATOR); // read
}
public List<ApplicationInfo> getList(){ // vethod return list
return list;
}
@Override
public void writeToParcel(Parcel dest, int flags) { // write
dest.writeTypedList(list);
}
@Override
public int describeContents() {
return 0;
}
CREATOR...
}
//Admission List to the Fragment in onCreateView()
MakingListObject obj = (MakingListObject)this.getArguments().getParcelable("List"); // NPE ERROR
List<ApplicationInfo> listData = obj.getList();
答案 0 :(得分:0)
您必须先启动列表。
public MakingListObject(Parcel in) {
list = new ArrayList<ApplicationInfo>;
in.readTypedList(list, ApplicationInfo.CREATOR); // read
}
答案 1 :(得分:0)
使用
存储Parcelable
的列表
Bundle dataToSend = new Bundle();
ArrayList<? super Parcelable> list = new ArrayList<>();
//add items here
....
dataToSend.putParcelableArrayList("foo", list);
并使用
阅读 Bundle receivedData = ...
receivedData.getParcelableArrayList("foo")
希望这会有所帮助