Question

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.

Was it helpful?

Solution 2

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");

OTHER TIPS

args.putParcelableArrayList(DATA_KEY, new ArrayList<>(data));

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);

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

Unfortunately, this did not work in my case. I ended up converting my array list to string (or JSON string) and send by

bundle.putString()

and then, in fragment, parsed the string back to array list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top