Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When call initLoader in Fragment?

I have pretty simple Fragment with ListView, CursorLoader and CursorAdapter. Everything is in single activity (just switching fragments). My problem is that onLoadFinished() is called in some situations twice based on where I put initLoader() call. Those situations are:

  • configuration change (rotating screen etc.)
  • replacing current fragment with another using FragmentTransaction and then returning back (popping backstack). In this case detail fragment of one list item.

When initLoader() is put in onCreateView(), onActivityCreated() (recommended in documentation) onLoadFinished() is called twice after configuration change. There is explanation why by Rudik Krasniynos. But onLoadFinished() is called only once when popping newer fragment from backstack.

When initLoader() is placed in onResume()/onStart() method situation from above is reversed. Two calls onLoadFinished() for popping backstack and one for configuration change.

So the question is where or how to init Loader without calling onLoadFinished() twice or what to check to not init Loader twice. Thanks!

Code for replacing fragment:

FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.root_view, fragment, tag);
ft.addToBackStack(null);
ft.commit();

Code for CursorAdapter:

//onCreateView
MyCursorAdapter mAdapter = new MyCursorAdapter(getActivity(), null, 0);
mList.setAdapter(mAdapter);
//in other/same lifecycle callbacks
getLoaderManager().initLoader(ID, null, this);

I'm using support library v18.

like image 973
Warlock Avatar asked Sep 10 '13 19:09

Warlock


2 Answers

To avoid onLoadFinished to be called more than once init your loader in onResume.

like image 193
MineConsulting SRL Avatar answered Sep 30 '22 02:09

MineConsulting SRL


I call it in onCreate and as far as I know this is the best practice... I'm using it right now and all work perfectly.

@Override
    protected void onCreate(Bundle savedInstanceState)

                             .......

          getSupportLoaderManager().initLoader(LOADER_ID, null, this);

                             .......
}
like image 44
Yurets Avatar answered Sep 30 '22 02:09

Yurets