I have a doubt about the use of Loader.
In my case, I call my own class that extends AsyncTaskLoader and return a List of MyObject.
public class MyActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<MyObject>> {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
getLoaderManager().initLoader(1, null, this);
getLoaderManager().initLoader(2_ID, null, this);
getLoaderManager().initLoader(3_ID, null, this);
...
}
}
My question is: can I run many Loader at the same time on the same Activity?
Will every Loader, when its loadInBackground() method is finished, call the onLoadFinished() method impemented in my Activity?
Thank you in advance.
Yes we can run many loaders at a time in one activity with unique ids, because Loader is a Asynchronous process. Please find below sample template.
public class SampleActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
initLoaders();
}
private void initLoaders() {
getLoaderManager().initLoader(1, null, null);
getLoaderManager().initLoader(2, null, null);
getLoaderManager().initLoader(3, null, null);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader = null;
switch (id) {
case 1:
cursorLoader = new CursorLoader(this, CONTENT_URI,
PROJECTION, selection, null, null);
break;
case 2:
cursorLoader = new CursorLoader(this, CONTENT_URI,
PROJECTION, selection, null, null);
break;
case 3:
cursorLoader = new CursorLoader(this, CONTENT_URI,
PROJECTION, selection, null, null);
break;
}
return cursorLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case 1:
if (data != null && data.getCount() > 0)
setData1();
break;
case 2:
if (data != null && data.getCount() > 0)
setData2();
break;
case 3:
if (data != null && data.getCount() > 0)
setData3();
break;
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}