0

I'm writing an Android application that streams live radio. I've set up an async task to display a progress dialog whilst the stream is loading. This works fine, however when it encounters a stream that is "down" and not functioning my app crashes and I just want to know the best way to handle the error.

Here is the code:

public class loadingData extends AsyncTask<Object, Object, Object>{


    protected void onPreExecute() {

        progDialog = new ProgressDialog(radioplayer.this);
            progDialog.setMessage("Loading radio station");
            progDialog.setIndeterminate(true);
            progDialog.setCancelable(false);
            progDialog.show();

    }   
    protected Object doInBackground(Object... arg0) {

        prs.setStation(strStation);        
        return null;
    }   
    protected void onCancelled() {

        super.onCancelled();
    }
    protected void onPostExecute(Object result) {

        progDialog.hide();
    }
    protected void onProgressUpdate(Object... values) {     
    }   
}
Hiral Vadodaria
  • 19,158
  • 5
  • 39
  • 56
user615099
  • 115
  • 2
  • 12

2 Answers2

1

Duplicate of this

If you use Roboguice there is a build in way of handling exceptions in async tasks.

Community
  • 1
  • 1
michael
  • 31
  • 5
0

What you can do (I'm using this trick in my app) is this:

protected Object doInBackground(Object... arg0) {
    try {
        prs.setStation(strStation);
        return null;
    }
    catch(Exception ex)
    {
        return ex;
    }
}


protected void onPostExecute(Object result) {
    progDialog.hide();         
    if(result != null && result instanceof Exception) {
        String errText = ((Exception)result).getMessage();
        //now deal with your exception on the UI thread
    }
}
Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • 1
    -1 I think this is pretty ugly, especially the Object return type. If you must combine exception handling and return values at least declare the function return as Exception. But even so the idea of returning null or an exception seems smelly. – Elemental Jan 11 '12 at 13:18
  • Thanks for explaining the '-1'. In my code I do not return `Object` type, but rather return `String`, which is either `null` or contains the error message. It serves my purpose. I kept `Object` return type, as it was given by the person asking the question. – Aleks G Jan 11 '12 at 13:25
  • Aleks Thank you, thank you , thank you!! It works like a charm and saved me a lot of time. Cheers. – user615099 Jan 11 '12 at 13:56