Reputation: 15976
How to gracefully display a Toast when an IOException occurs inside the doInBackground of an AsyncTask?
Upvotes: 0
Views: 1212
Reputation: 504
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.
Upvotes: 0
Reputation: 9189
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.
Upvotes: 1
Reputation: 4753
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;
}
Upvotes: 2