Skip to content

Instantly share code, notes, and snippets.

@codebutler
Created May 10, 2012 21:32
Show Gist options
  • Save codebutler/2656040 to your computer and use it in GitHub Desktop.
Save codebutler/2656040 to your computer and use it in GitHub Desktop.
Extension of AsyncTask that provides loading/error dialogs.
import android.support.v4.content.AsyncTaskLoader;
import android.content.Context;
import android.os.Handler;
import android.text.format.DateUtils;
public abstract class BetterAsyncLoader<T> extends AsyncTaskLoader<T> {
private T mData;
private long mPollInterval;
private Handler mRepeatHandler;
public static final long INTERVAL_NONE = -1;
public static final long INTERVAL_SHORT = DateUtils.SECOND_IN_MILLIS * 15;
public static final long INTERVAL_LONG = DateUtils.MINUTE_IN_MILLIS;
public BetterAsyncLoader(Context context, long pollingInterval) {
super(context);
if (pollingInterval > 0) {
mPollInterval = pollingInterval;
mRepeatHandler = new Handler();
}
}
@Override
public void deliverResult(T data) {
if (isReset()) {
// An async query came in while the loader is stopped
return;
}
this.mData = data;
super.deliverResult(data);
if (mRepeatHandler != null) {
startTimer();
}
}
@Override
protected void onStartLoading() {
if (mData != null) {
deliverResult(mData);
}
if (takeContentChanged() || mData == null) {
forceLoad();
}
}
@Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
mData = null;
}
private void startTimer() {
mRepeatHandler.postDelayed(new Runnable() {
public void run() {
onContentChanged();
}
}, mPollInterval);
}
}
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ProgressBar;
public abstract class BetterAsyncTask<Result> extends AsyncTask<Void, ProgressBar, BetterAsyncTask.TaskResult<Result>> {
private static final String TAG = "BetterAsyncTask";
private ProgressDialog mProgressDialog;
private Activity mActivity;
private boolean mFinishOnError;
public BetterAsyncTask(Activity activity) {
this(activity, true);
}
public BetterAsyncTask(Activity activity, boolean showLoading) {
this(activity, showLoading, null, false);
}
public BetterAsyncTask(Activity activity, boolean showLoading, boolean finishOnError) {
this(activity, showLoading, null, finishOnError);
}
public BetterAsyncTask(Activity activity, boolean showLoading, int loadingText) {
this(activity, showLoading, activity.getString(loadingText));
}
public BetterAsyncTask(Activity activity, boolean showLoading, String loadingText) {
this(activity, showLoading, loadingText, false);
}
public BetterAsyncTask(Activity activity, boolean showLoading, String loadingText, boolean finishOnError) {
mActivity = activity;
mFinishOnError = finishOnError;
if (showLoading) {
mProgressDialog = new ProgressDialog(mActivity);
mProgressDialog.setCancelable(false);
mProgressDialog.setIndeterminate(true);
setLoadingText(loadingText);
}
}
public void cancelIfRunning() {
if (getStatus() != AsyncTask.Status.FINISHED) {
super.cancel(true);
}
if (mProgressDialog != null) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
protected void setLoadingText(String text) {
if (mProgressDialog == null) {
return;
}
mProgressDialog.setMessage(TextUtils.isEmpty(text) ? mActivity.getString(R.string.loading) : text);
}
@Override
protected final TaskResult<Result> doInBackground(Void... unused) {
try {
return new TaskResult<Result>(doInBackground());
} catch (Exception e) {
Log.e(TAG, "Error in task:", e);
return new TaskResult<Result>(e);
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (mProgressDialog != null)
mProgressDialog.show();
}
@Override
protected final void onPostExecute(TaskResult<Result> result) {
if (mProgressDialog != null)
mProgressDialog.dismiss();
if (!result.success()) {
onError(result.getException());
return;
}
onResult(result.getObject());
}
protected void onError(Exception ex) {
AlertDialog dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.error)
.setMessage(ex.toString())
.setPositiveButton(android.R.string.ok, null)
.create();
if (mFinishOnError) {
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
mActivity.finish();
}
});
}
dialog.show();
}
protected abstract Result doInBackground() throws Exception;
protected abstract void onResult(Result result);
public static class TaskResult<T> {
private final T mObject;
private final Exception mException;
public TaskResult(T object) {
if (object == null) {
throw new IllegalArgumentException("object may not be null");
}
mObject = object;
mException = null;
}
public TaskResult(Exception exception) {
if (exception == null) {
throw new IllegalArgumentException("exception may not be null");
}
mException = exception;
mObject = null;
}
public T getObject() {
return mObject;
}
public Exception getException() {
return mException;
}
public boolean success() {
return (mException == null);
}
}
}
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Log;
import static com.tagstand.writer.ui.BetterAsyncTask.TaskResult;
public abstract class ListLoaderCallbacks<T> implements LoaderManager.LoaderCallbacks<TaskResult<T>> {
private ListFragment mFragment;
public ListLoaderCallbacks(ListFragment fragment) {
mFragment = fragment;
}
public final void onLoadFinished(Loader<TaskResult<T>> loader, TaskResult<T> data) {
if (data.success()) {
onLoadFinished(data.getObject());
} else {
Log.e(mFragment.getClass().getName(), "Error in loader", data.getException());
mFragment.setEmptyText(data.getException().toString());
onLoadFinished(null);
}
}
public void onLoaderReset(Loader<TaskResult<T>> loader) {
if (!mFragment.isVisible()) {
return;
}
mFragment.setEmptyText(null);
mFragment.setListAdapter(null);
}
protected abstract void onLoadFinished(T result);
}
@herozhou1314
Copy link

good it`s work for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment