1

I have a list like fragment, and currently I am passing in info like so:

Fragment:

public void populate(Map<String, List<Book>> booksGroupedByType)
{
    BookListAdapter bookListAdapter = new BookListAdapter(this.getActivity(), booksGroupedByType);
    _lstBooks.setAdapter(bookListAdapter);
}

Activity:

private void populateBooksFragment()
{
    Map<String, List<Book>> booksGroupedByType = _repository.getAllBooksGroupedByType();
    BookListFragment bookListFragment = (BookListFragment) getFragment(R.id.fragBooks);
    if (bookListFragment != null)
    {
        bookListFragment.populate(booksGroupedByType);
    }
}

Then I felt it would be better if I could pass this information when creating the fragment, since we have no constructor available I looked up the method and found this:

public static DetailsFragment newInstance(int index) {
    DetailsFragment f = new DetailsFragment();
    // Supply index input as an argument.
    Bundle args = new Bundle();
    args.putInt("index", index);
    f.setArguments(args);
    return f;
}

I tried to implement, but found my Map was not serializable as it was and needed more work. So my question is, why go through this? is there a disadvantage to using my original approach (populate), which would even be faster than serializing?

I thought perhaps my fragment will lose its data when rotated, but no, when rotating (in emulator) the list was kept intact.

sprocket12
  • 5,368
  • 18
  • 64
  • 133
  • This answers your question nicely http://stackoverflow.com/questions/10450348/do-fragments-really-need-an-empty-constructor – Rohit5k2 Jan 30 '15 at 21:40
  • @Rohit5k2 I am not using a constructor at all, so is restoring state the only issue left? I did device rotation but that did not mess anything up... – sprocket12 Jan 30 '15 at 21:45

1 Answers1

0

Let's say you have some data obtained in time/resource consuming way. If you don't want to download them each time configuration changes (and activity is destroyed), you have to somehow persist them.

First option is to put data into the bundle, so it will be available for the fragment even after it is autorecreated by the system. It may work for simple types, but for arbitrary object it's usually not an option because of performance reasons (serialization/parcelization).

Second option would be retaining the fragment, by setting a flag in fragment's onCreate():

setRetainInstanceState(true)

In that case fragment won't be destroyed after configuration change, but just detached from activity being destroyed, and attached to the new one. Any data you will pass e.g. via setters will be available too.

See also: Understanding Fragment's setRetainInstance(boolean)

Community
  • 1
  • 1
Zbigniew Malinowski
  • 1,034
  • 1
  • 9
  • 22