I am making a simple news application.
Its MainActivity contains a ViewPager with TabLayout that hosts different fragments for news categories.
The first two categories are Business (first) Sports (Second).
The problem is that the content of these two fragments comes out to be same even though different loaders are used, i.e. 'Business' tab shows Sports news.
But when you swipe 3rd fragment, the problem gets resolved. (Probably because ViewPager reloads the first fragment.)
The fragment has implemented Cursor Loader callbacks
public class ArticleListFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>
In Fragment's #onCreate
, I call the Loader:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
Bundle bundle = getArguments();
loader_id = bundle.getInt("id");
category = bundle.getString("category");
getLoaderManager().initLoader(loader_id, null, this);
}
Fragment's loader callbacks are as follows:
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
if(cursorLoader.getId() == loader_id){
if(cursor != null && cursor.getCount() > 0) {
Log.i("haha","id: " + cursorLoader.getId());
adapter.swapCursor(cursor);
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
MyPagerAdapter
has the following implementation of getItem()
:
@Override
public Fragment getItem(int position) {
ArticleListFragment fragment = ArticleListFragment.newInstance();
Bundle bundle = new Bundle();
bundle.putString("category", categories.get(position));
bundle.putInt("id",position);
fragment.setArguments(bundle);
return fragment;
}