Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass Arraylist in Activity to Fragment

I have MyClass implements Parcelable. And have 2 fragments. In MainActivity (onCreate) i have code:

ArrayList<MyClass> data = new ArrayList<MyClass>();
............
Bundle extras1 = new Bundle();
extras1.putParcelableArrayList("arraylist", data);
Tab1Fragment fg = new Tab1Fragment();
fg.setArguments(extras1);

And in Fragment(onCreateView):

Bundle extras = getArguments(); 
ListView list = (ListView) content.findViewById(R.id.lvMain);
if (extras != null) {
    data = extras.getParcelableArrayList("arraylist");
    list.setAdapter(new MyAdapter(getActivity(), data));
}

But extras alway null.why?:)

like image 498
NickDevil Avatar asked Oct 21 '22 16:10

NickDevil


1 Answers

Your provided code seems fine. I suspect the problem is from the how you implement MyClass. A typical implementation of Parcelable is something like this (taken from google)

public class MyParcelable implements Parcelable {
 private int mData;

 public int describeContents() {
     return 0;
 }

 public void writeToParcel(Parcel out, int flags) {
     out.writeInt(mData);
 }

 public static final Parcelable.Creator<MyParcelable> CREATOR
         = new Parcelable.Creator<MyParcelable>() {
     public MyParcelable createFromParcel(Parcel in) {
         return new MyParcelable(in);
     }

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

 private MyParcelable(Parcel in) {
     mData = in.readInt();
 }
like image 78
Lowkey Avatar answered Nov 09 '22 14:11

Lowkey