在使用Retrofit並使用非同步回調消費了json之後,我無法將ArrayList從MainActivity傳遞到片段。從MainActivity在片段之間傳遞ArrayList和Parcelable
代碼:
lFragmentManager = getFragmentManager();
lFragment = lFragmentManager.findFragmentById(R.id.frame_container);
lFragment = new Fragment_Categories();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("list_categories", Categories_.getCategories());
//for(int a = 0 ; a < Categories_.getCategories().size(); a++)
// Log.d("billy",Categories_.getCategories().get(a).getTitle());
lFragment.setArguments(bundle);
lFragmentManager.beginTransaction().replace(R.id.frame_container ,lFragment).commit();
注意,在註釋日誌並打印清單的背景下,所以我把ArrayList
與此代碼片段裏面onCreateView
:
if(savedInstanceState != null)
categories = savedInstanceState.getParcelableArrayList("list_categories");
/*
* initialize the Recycler view
*/
mRecycler = (RecyclerView)view.findViewById(R.id.categories_list);
mAdapter = new AdapterCategories(categories,getActivity());
mRecycler.setAdapter(mAdapter);
這是我的班級類別:
public class Categories implements Parcelable{
private ArrayList<NavDrawerItem> categories;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(categories);
}
public static final Parcelable.Creator<Categories> CREATOR = new Parcelable.Creator<Categories>() {
public Categories createFromParcel(Parcel in) {
return new Categories(in);
}
public Categories[] newArray(int size){
return new Categories[size];
}
};
private Categories(Parcel in){
categories = in.createTypedArrayList(NavDrawerItem.CREATOR);
}
public ArrayList<NavDrawerItem> getCategories() {
return categories;
}
}
這裏是類NavDrawerItem:
public class NavDrawerItem implements Parcelable {
private String title;
private String description;
private String image;
private String post_count;
private String id;
private String slug;
private int parent;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(description);
dest.writeString(image);
dest.writeString(post_count);
dest.writeString(id);
dest.writeString(slug);
dest.writeInt(parent);
}
public static final Parcelable.Creator<NavDrawerItem> CREATOR = new Parcelable.Creator<NavDrawerItem>() {
public NavDrawerItem createFromParcel(Parcel in) {
return new NavDrawerItem(in);
}
public NavDrawerItem[] newArray(int size){
return new NavDrawerItem[size];
}
};
private NavDrawerItem(Parcel in){
title = in.readString();
description = in.readString();
image = in.readString();
post_count = in.readString();
id = in.readString();
slug = in.readString();
parent = in.readInt();
}
的問題是,內部片段(試圖通過列表的RecyclerView
的適配器時)或RecyclerView
我拿一個空異常的轉接器內:
顯示java.lang.NullPointerException:嘗試上的空對象引用調用虛擬方法的java.util.ArrayList android.os.Bundle.getParcelableArrayList(java.lang.String中)'
謝謝你的幫助!
是的,我沒有看到那個謝謝! – Vasilisfoo
是的,我嘗試但它有等待時間 – Vasilisfoo