Skip to content

Instantly share code, notes, and snippets.

@andrewmarmion
Last active March 14, 2017 17:00
Show Gist options
  • Select an option

  • Save andrewmarmion/8a4a099245ec84475beff331bdcbc0d5 to your computer and use it in GitHub Desktop.

Select an option

Save andrewmarmion/8a4a099245ec84475beff331bdcbc0d5 to your computer and use it in GitHub Desktop.
How to create a AsyncTask that is in it's own class
//Create an interface called AsyncResponse, AsyncResponse.java
public interface AsyncResponse {
void processFinish(String response);
}
// In the MainActivity.java override processFinish
// In processFinish put everything that you want to happen when you get a response from the AsyncTask
public class MainActivity extends Activity implements AsyncResponse {
protected void onCreate() {
MyAsyncTask myAsyncTask = new MyAsyncTask(this);
myAsynchTask.execute(URL);
@Override
public void processFinish(String response) {
// use the response and do whatever UI updates you want here.
}
}
//Create a separate file/class for your AsyncTask, MyAsyncTask.java
public class MyAsyncTask extends AsyncTask<URL, Void, String> {
// Set up the delegate
public AsyncResponse delegate = null;
public MyAsyncTask(AsyncResponse delegate) {
this.delegate = delegate;
}
@Override
protected String doInBackground(URL... params) {
URL url = params[0];
String result = url.itString();
return result;
}
@Override
protected void onPostExecute(String result) {
System.out.println("result from download (MyAsyncTask): " + result);
delegate.processFinish(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment