Skip to content

Instantly share code, notes, and snippets.

@sabiou
Forked from cesarferreira/AsyncTaskActivity.java
Created January 23, 2019 01:42
Show Gist options
  • Save sabiou/e0504f327f05f6e91c7432e6fb33a465 to your computer and use it in GitHub Desktop.
Save sabiou/e0504f327f05f6e91c7432e6fb33a465 to your computer and use it in GitHub Desktop.
Advanced Android AsyncTask Callback example
package com.cesarferreira.asynctaskcallback;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SomeTask someTask = new SomeTask(getApplicationContext(), new OnEventListener<String>() {
@Override
public void onSuccess(String result) {
Toast.makeText(getApplicationContext(), "SUCCESS: "+result, Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Exception e) {
Toast.makeText(getApplicationContext(), "ERROR: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
someTask.execute();
}
}
package com.cesarferreira.asynctaskcallback;
/**
* Created by cesarferreira on 30/05/14.
*/
public interface OnEventListener<T> {
public void onSuccess(T object);
public void onFailure(Exception e);
}
package com.cesarferreira.asynctaskcallback;
import android.content.Context;
import android.os.AsyncTask;
/**
* Created by cesarferreira on 22/05/14.
*/
public class SomeTask extends AsyncTask<Void, Void, String> {
private OnEventListener<String> mCallBack;
private Context mContext;
public Exception mException;
public SomeTask(Context context, OnEventListener callback) {
mCallBack = callback;
mContext = context;
}
@Override
protected String doInBackground(Void... params) {
try {
// todo try to do something dangerous
return "HELLO";
} catch (Exception e) {
mException = e;
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (mCallBack != null) {
if (mException == null) {
mCallBack.onSuccess(result);
} else {
mCallBack.onFailure(mException);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment