Search code examples
androidandroid-fragmentsandroid-listfragment

Calling an async task from a button click in a listitem inside of a fragment


My app has a NavigationDrawer activity that swaps fragments based on the selection. One of these fragments contains a listview with several buttons. The listview items themselves are not selectable, but the I need to handle the button clicks, which I'm able to do capture successfully in my custom adapter.

Here is my issue: some button clicks need to trigger an async task to call REST api urls. I'm not sure how to do this. I tried calling a static method on my fragment that would instantiate an instance of a private class (extends AsyncTask), but that won't work. I thought about making a private class inside my custom adapter that extends from AsyncTask, but that doesn't feel right. What's the proper way to do something like this?


Solution

  • It wouldn't be different then Async tasks from anywhere else. Take a look at the documentation

    http://developer.android.com/intl/es/reference/android/os/AsyncTask.html

    Create a class for your task

     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));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }
    
     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }
    
     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
    }
    

    Then create an instance of it in your onClick event

     new DownloadFilesTask().execute(url1, url2, url3);