开发者

Gracefully handle IOException inside AsyncTask?

How to gracefully display a Toast when an IOException occurs inside the doInBac开发者_高级运维kground of an AsyncTask?


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;
 }


Just like this:

Toast.makeText(Context context, int resId, int duration).show();

It needs a Context so just pass it along to the AsyncTask. More information.


A dirty way is to create a different result in your IOException, for example if there is no internet connection you can check the connectivity in your IOException and set your result if connection exists to result='connection_to_server_issue' . If there is no connection result='no_connection'.

And later on on your postExecution you can check first your result if equals on of these two strings, and if so just execute a toastmessage, or whatever you want do do if one of these errors occurs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜