Search code examples
android-layoutandroidandroid-networking

Gracefully handle IOException inside AsyncTask?


How to gracefully display a Toast when an IOException occurs inside the doInBackground of an AsyncTask?


Solution

  • You can override either onPostExecute or onProgressUpdate to display messages on the UI thread.

    To use onProgressDisplay declare the second type as String when you extend AsyncTask:

    private class YourTask extends AsyncTask<ParamType, String, ReturnType> {
    

    and override onProgressUpdate:

    protected void onProgressUpdate(String... progress) {
         String errMsg = progress[0];
         Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_SHORT).show();
    }
    

    then you can call the "progress" function when your exception occurs in doInBackground:

    protected ReturnType doInBackground(ParamType... params) {
         try {
             // do stuff
         } catch (IOException e) {
            publishProgress("My Error Msg goes here");
         }
         return result;
     }