1

How can I deal with Objects and threads in Android? I am trying to see if there is a way to use AsyncTask Class (doInBackground() and onPostExecute() methods) with Objects rather than Strings. I would also like to interact with the UI.

Is there a good tutorial to start from or any hint?

Thanks

0

1 Answer 1

1

You can subclass AsyncTask like in the following example.

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
  protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
     }
     return totalSize;
  }

  protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
  }

  protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
  }
}

In this example "URL" is the parameter type, Long is the result type (passed to onPostExecute()) and Integer is an optional progress indicator. Parameter type, progress type and result type can be of type "Void" if they are unused.

You can find this example and a longer explanation here

The interaction with the ui has to happen in onPostExecute().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.