Last active
March 14, 2017 17:00
-
-
Save andrewmarmion/8a4a099245ec84475beff331bdcbc0d5 to your computer and use it in GitHub Desktop.
How to create a AsyncTask that is in it's own class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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