Search code examples
androidmultithreadinglistviewandroid-asynctaskrestful-architecture

Dealing with AsyncTask with Objects rather than Strings


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


Solution

  • 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().