Skip to content

Instantly share code, notes, and snippets.

@csabafarkas
Last active September 7, 2018 14:09
Show Gist options
  • Save csabafarkas/73c1d5d82b69ef31b120b5c066afb26e to your computer and use it in GitHub Desktop.
Save csabafarkas/73c1d5d82b69ef31b120b5c066afb26e to your computer and use it in GitHub Desktop.
AsyncTaskLoader
// implement LoaderManager.LoaderCallbacks<String> on MainActivity
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<String> {
// Create a constant int to uniquely identify loader
private static final int LOADER_ID = 101;
private static final String KEY = "key";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the loader with LOADER_ID as the ID, null for the bundle, and this for the context
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
}
private void doSomeFancyLoading() {
// create a bundle
Bundle queryBundle = new Bundle();
queryBundle.putString(KEY, "we save this text");
// call getSupportLoaderManager and store it in a LoaderManager variable
LoaderManager loaderManager = getSupportLoaderManager();
// get our Loader by calling getLoader and passing the ID we specified
Loader<String> loader = loaderManager.getLoader(LOADER_ID);
// if the Loader was null, initialize it. Else, restart it.
if (loader == null)
loaderManager.initLoader(LOADER_ID, queryBundle, this);
else
loaderManager.restartLoader(LOADER_ID, queryBundle, this);
}
// Override onCreateLoader
@Override
public Loader<String> onCreateLoader(int id, final Bundle args) {
// cache result
private String mResult;
// return a new AsyncTaskLoader<String> as an anonymous inner class with this as the constructor's parameter
return new AsyncTaskLoader<String>(this) {
// override onStartLoading
@Override
protected void onStartLoading() {
super.onStartLoading();
if (args == null) return;
// if mResult != null => deliver result
if (mResult != null) {
deliverResult(mResult);
return;
}
forceLoad();
}
// override loadInBackground
@Override
public String loadInBackground() {
String persistedString = args.getString(KEY);
if (TextUtils.isEmpty(persistedString)) return null;
try {
// do some long network-related task here
return postStringToRestApi(persistedString);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
public void deliverResult(String data) {
mResult = data;
super.deliverResult(mResult);
}
};
}
// override onLoadFinished
@Override
public void onLoadFinished(Loader<String> loader, String data) {
if (!TextUtils.isEmpty(data)) {
System.out.println(data);
} else {
System.out.prinln("no data was returned");
}
}
// override onLoaderReset
@Override
public void onLoaderReset(Loader<String> loader) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment