Instantiate a fragment with a Custom Object Array List part II

时间:2017-04-06 16:55:37

标签: java android android-fragments

Hi I searched for this question in stackoverflow.com and I found a this post

Instantiate a fragment with a Custom Object Array List

And all the answers are Serializer or Parceable, I made this soluction.

My question, is a good Idea or is a bad practice?.

The Object IconItem

public class IconItem {

private String name;
private int resId;

public IconItem(String name, int resId){
    this.name = name;
    this.resId = resId;
}

public String getName(){
    return this.name;
}

public int getResId(){
    return this.resId;
}

}

The fragment

public class IconsFragment extends Fragment {

private ArrayList<IconItem> myList

public static IconsFragment newInstance(ArrayList<IconItem> list) {
    IconsFragment fragment = new IconsFragment();

    myList = list;

    return fragment;
}

}

with this I pass the ArrayList when I instance the fragment.

For me work with a RecyclerView in other Fragment.

Regards

1 个答案:

答案 0 :(得分:0)

Its a bad practice, as you are passing an entire list of custom object to the initialzer method of the fragment, and yes, most of the post will guide to make it serializable or parcelable because:

For serialization, creates short term storage of almost-arbitrary objects refer this

For Parcelable: on the other hand is much of an Android SDK thing.

You can see good SO posts about Parcelable vs Serializable and a good onehere

Parcelable and serialization both help in marshalling and unmarshalling the java objects, hence saving heap space. So you objects are not passed directly they are compressed (sort of, not really) and then forwarded hence extensively recommeded.

And as far as why your approach is not good and recommended, you are sending and entire array of custom objects over a method, if your array list size is too big, you might encounter an OOM.

Sending a huge array list over a parcelable is also not recommended, as it throws a transaction exception, which looks something like this:

Fatal Exception: java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 1791812 bytes

But for small custom object lists (<5000) i dont think parcelable gives any errors. though also depends on how huge the custom objects are!