I wanted to pass arraylist of objects from one fragment to another i tried the following ways, wanted to know what are the pro's and con's of the following or is their any better approach
First
public myFragment(ArrayList<E> myarray) {
super();
this.myarray=myarray;
}
In the above code i created a constructor in the fragment class and used it to modify the arraylist but as i read from net this is not the best practice i searched for other's
Second
public static myFragment newInstance(ArrayList<E> myarray1) {
// TODO Auto-generated constructor stub
MyFragment myFragment=new MyFragment();
myarray=myarray1;
}
here i created a static method which modify's the static arraylist myarray
Third
public static myFragment newInstance(ArrayList<E> myarray1) {
// TODO Auto-generated constructor stub
MyFragment myFragment=new MyFragment();
Bundle bundle=new Bundle();
bundle.putSerializable(TAG,myarray1);
myFragment.setArguments(bundle);
return myFragment;
}
In this code i created a Serializable arraylist and passed it to bundel then
myarray=(ArrayList<E>) bundle.getSerializable(TAG);
retrived the arraylist from bundle
Fourth
the forth method which i got on net was using parcelable instead of Serializable but it was bit difficult to create a parcelable, if any one can share easy way to create a parceable as i have array list inside arraylist.
So which of them is best approach or is their any better approach to send custom object from one fragment to another and what are their pro's and con's
1) You shouldn't ever override
Fragment's
constructor, it will cause unexpected crashes when system tries to recreate the fragment using the reflection.2) You shouldn't use static
ArrayList
to hold the data because if you run into situation where you want to instatiate two fragments of the same kind, one will override the data from the second one3)
Serializable
is acceptable way, but it's rather slow compared to theParcelable
since it uses reflection to restore your data4)
Parcelable
is a way to go. It's a bit of pain to make your classParcelable
but it's way faster than option 3., and safer than options 1. and 2.another ideas:
5) If you don't need to persist the data, you can construct a singleton class which will hold the data in the
ArrayList
, and you can access it from anywhere in the application6) If you need to persist the data, you should store it in the database, and when you go from one
Activity
to antoher, or from oneFragment
to another, you just pass the ID of the object in question and pull the data from DB.