AsyncTask

How to set up an AsyncTask to take a task off the main thread

Can override the following:
Params -> doInBackground // Runs on background thread – only method we MUST override
Progress -> onProgressUpdate // Runs on main thread Call publishProgress as many times as you want during process
Result -> onPostExecute // Runs on main thread
(Also a onPreExecute function) // Runs on main thread

Initiates the task on a background thread and when it has finished runs onPostExecute. Takes three parameters:

  • Params - the type of the parameters sent to the task upon execution
  • Progress - the type of the progress units published during the background computation
  • Result - the type of the result of the background computation
    public class AsyncQueryTask extends AsyncTask<URL, Void, String> { // The first param is a ... which is technically passed as an array
        @Override
        protected String doInBackground(URL... params) { // First param (array) is passed in
            URL searchUrl = params[0]; // In this instance we only use the first URL in the array
            String githubSearchResults = null;
            try {
                githubSearchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return githubSearchResults;
        }

        @Override
        protected void onPostExecute(String s) { // String from doInBackground passed in here
            if (s != null & !s.equals("")) {
                mSearchResultsTextView.setText(s);
            }
        }
    }

Call 'execute' with params to begin the task

new AsyncQueryTask().execute(searchUrl);

If writing a self-executing Asynctask, call .execute() at the end of the instantiation:

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                // Do something
            }
        }.execute();

ud851-Exercises-student\Lesson02-GitHub-Repo-Search\T02.06-Exercise-AddPolish