I am having difficulty implementing loaders properly. I read a lot of articles and stackoverflow posts, and tried various things. But nothing has solved this problem yet. I am using a viewpager with PagerSlidingTabStrip library to create a 3 tab layout (using FragmentPagerAdapter). And I am using 3 separate loaders to load data for these 3 tabs.
The problem is that when I first load my app, the adjacent tabs don't call loadInBackground() until I scroll over to those tabs even though FragmentPagerAdapter creates the adjacent fragments successfully. Strangely, once I rotate or press home and open the app again, the adjacent tabs start loading. This means that if the view gets destroyed and recreated, the loading begins.
I also tried using startLoading for the loaders in all 3 fragments (I believe my OnStartLoading method is properly configured. I am calling forceLoad() in that method). If I use startLoading, then loadInBackground() is called. And yet, onLoadFinished() isn't! And so my view still shows an empty spinning loader until I move to the adjacent tab.
So, in short, whether loadInBackground() is called or not, onLoadFinished() for adjacent pages is not called until the view gets recreated. (or of course if I simply move to those pages)
Anyone come across a similar problem? I feel like I have tried everything I can, and have no clue how to proceed with this issue.
Here's my onCreateView():
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.movie_grid, container, false);
LoaderManager lm = getLoaderManager();
lm.restartLoader(CONFIG_LOADER, null, new ConfigurationLoaderCallbacks());
lm.restartLoader(MOVIE_DATA_LOADER, null, new MovieDataLoaderCallbacks());
...
return v;
}
My abstract AsyncTaskLoader class:
private D mData;
public DataLoader(Context context) {
super(context);
}
@Override
protected void onStartLoading() {
if (mData != null) {
deliverResult(mData);
} else {
forceLoad();
}
}
@Override
public void deliverResult(D data) {
mData = data;
if (isStarted())
super.deliverResult(data);
}
My onResume():
public void onResume() {
super.onResume();
// Call this to re-connect with an existing loader
LoaderManager lm = getLoaderManager();
if (lm.getLoader(MOVIE_DATA_LOADER) != null) {
lm.initLoader(MOVIE_DATA_LOADER, null, new MovieDataLoaderCallbacks());
}
if (lm.getLoader(CONFIG_LOADER) != null) {
lm.initLoader(CONFIG_LOADER, null, new ConfigurationLoaderCallbacks());
}
}