Q:

User feedback from AsyncTask.doInBackground()?

I have an AsyncTask which which takes an ArrayList of music files to play. In the doInBackground method, I loop through the ArrayList and play the songs one-by-one. I'd like to put a status message on a TextView of the UI or something to indicate which song is playing, but getting the error Only the original thread that created a view hierarchy can touch its views.  If I only update the UI widgets from onPreExecute() and onPostExecute() the list has already been played. Is there a way to use onProgressUpdate or other AsyncTask method to do this?

A:

This is certainly possible.  Here's a basic example if you had Strings you wanted to display for song name, album name, and artist name (I haven't fully implemented the AsyncTask, just the parts relevant to onProgressUpdate):
private class myAsyncTask extends AsyncTask<Void, String, Void> 
{
     protected Void doInBackground(Void... voids) 
     {
         //Get some list of songs, named songs
         for(Song song in songs)//This is the loop where you're playing your songs
         {
             publishProgress(song.name, song.album, song.artist);
             //Play the song and wait for it to finish
         }
         return null;
     }

     protected void onProgressUpdate(String... songData) 
     {
         //Assuming three text views exist to display your data
         nameTextView.setText(songData[0]);
         albumTextView.setText(songData[1]);
         artistTextView.setText(songData[2]);
     }
}

The important things to note are the the second class in the angle brackets is the type of parameters for onProgressUpdate, and that publishProgress gets called in doInBackground to trigger onProgressUpdate.  Most examples that you'll find for onProgressUpdate involve increasing the fill on a ProgressBar, but the method runs on the UI thread and can interact with any Views that can be accessed by your AsyncTask.  If you're still having some trouble, post your current AsyncTask so that it'll be easier to help integrate this example class into what you already have. Here are the docs for AsyncTask for more information.Hope this helps!

