Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing custom List of data using Bundle

I'm developing a simple app, that contains tabview with fragment. I am stuck at the place, where i have to pass data to my newly created fragment on tabselect.

I have a List of lists of my custom class objects:

List<List<NewsObjectClass>> myList;

Here is where I got stuck:

public static class PlaceholderFragment extends ListFragment{

    private static final String ARG_SECTION_NUMBER = "section_number";


    public PlaceholderFragment(){       

    }


    public static PlaceholderFragment newInstance(int sectionNumber, List<List<NewsObjectsClass>> data)  {

        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);

        // Here i want to pass my List<List<NewsObjectClass>> to the bundle

        fragment.setArguments(args);
        return fragment;
    }
...

So specifically i need a way how to pass my list of lsits of myCustomObjects to the fragment, so there I could use it for lsitview adapter.

Any syggestions on how to pass this type of data would be great. Thanks.

like image 221
xenuit Avatar asked May 03 '14 06:05

xenuit


3 Answers

args.putParcelableArrayList(DATA_KEY, new ArrayList<>(data));
like image 94
Alireza Sobhani Avatar answered Oct 05 '22 23:10

Alireza Sobhani


Make your NewObjectClass Parcelable or Serializable and then create a new class, effectively, containing your list, also Parcelable or Serializable. Then use Bundle.putSerializable (or putParcelable)

Or, simpler, make NewObjectClass Parcelable then use putParcelableArrayList if you can do with ArrayList instead of generic List

Or, simplest, make NewObjectClass Serializable and use putSerializable passing ArrayList<NewObjectClass> because ArrayList is Serializable

In the last case perhaps you only will have to ad implements Serializable to your class.

Alternatively, if your data seem to be large, consider keeping them in a custom Application-derived object instead. You extend Application and then such object will exist all the time your app exist. Don't forget to register it in manifest.

class MyApplication extends Application {
   public static Object myData;
}

Or you can do with shared preferences

PreferenceManager.getDefaultSharedPreferences().edit().putInt("a", 1).commit();
PreferenceManager.getDefaultSharedPreferences().getInt("a");
like image 43
Alexander Kulyakhtin Avatar answered Oct 05 '22 23:10

Alexander Kulyakhtin


use putSerializable method to pass your custom list.

args.putSerializable(KEY, ArrayList<Type>);

and fetch it using getSerializable

ArrayList<Type> list = (ArrayList<Type>) getArguments().getSerializable(KEY);
like image 29
Konstantin Konopko Avatar answered Oct 05 '22 23:10

Konstantin Konopko