Skip to content

Instantly share code, notes, and snippets.

@JGeovani
Created March 29, 2017 14:17
Show Gist options
  • Save JGeovani/d587d425a5bf3705bbe767bbc3f9433f to your computer and use it in GitHub Desktop.
Save JGeovani/d587d425a5bf3705bbe767bbc3f9433f to your computer and use it in GitHub Desktop.
public class MainActivity
extends FragmentActivity
implements LoaderCallbacks<String> {
ProgressDialog dialog;
String json;
private static final int MEU_LOADER = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Recovering the status of the Activity
if (savedInstanceState != null) {
json = savedInstanceState.getString("valores");
updateScreen();
}
// This class manages all Loaders
LoaderManager lm = getSupportLoaderManager();
// If JSON has not yet been downloaded
if (json == null) {
// Displays the dialog
dialog = ProgressDialog.show(
this, "Wait...", "Downloading tweets");
// And initializes the Loader (if it has already been initialized, it will just continue)
lm.initLoader(MEU_LOADER, null, this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// If you are viewing progress, remove it
if (dialog != null && dialog.isShowing())
dialog.dismiss();
}
@Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
// Saving the status of the Activity
outState.putString("valores", json);
}
// Interface Methods LoaderCallbacks
@Override
public Loader<String> onCreateLoader(
int id, Bundle args) {
// Instances and returns the AsyncTaskLoader
return new MinhaAsyncTask(this);
}
@Override
public void onLoadFinished(Loader<String> loader,
String data) {
// Called when the Loader finishes its work
// Here, we assign the result to the json attribute and hide the dialog
json = data;
updateScreen();
dialog.dismiss();
}
@Override
public void onLoaderReset(Loader<String> loader) {
// Called if the Loader is reset
Log.d("NGVL", "onLoaderReset");
}
// AsyncTaskLoader
public static class MinhaAsyncTask
extends AsyncTaskLoader<String> {
// The downloaded JSON will be stored here to be passed to Activity
String data;
public MinhaAsyncTask(Context context) {
super(context);
}
@Override
protected void onStartLoading() {
// If you have not downloaded the data, do it now!
if (data == null) {
forceLoad();
// If you have already downloaded, just deliver the result
} else {
deliverResult(data);
}
}
@Override
public String loadInBackground() {
// In this method the JSON will be downloaded
return downloadJSON();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment