androidlistandroid-fragmentsbundlecustom-object

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.


Solution

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