I am following the guide on Processes and Threads to implement an AsyncTask
in an android activity in which I will perform some database access. However, my code has to handle an exception in doInBackground
.
My current thinking is to provide a Toast
popup to inform the user of this exception, but now I am afraid this too " violates the second rule of the single-threaded model: do not access the Android UI toolkit from outside the UI thread " (as per the guide).
Would I be wrong in providing a Toast popup? Is there a better way to handle exceptions in the doInBackground
method?
Will the exception cause you to stop what doInBackground
is processing?
If yes, store what exception you encountered, exit doInBackground
and show the Toast in onPostExecute
If no, pass the exception information to onProgressUpdate
with publishProgress
.
Trying to pop-up the Toast
in doInBackground
will not work.
You can use runOnUIThread
to update UI from background thread
@Override
protected void doInBackground(Void... params) {
try{
// do some stuff
}catch(Exception ex){
ex.printStackTrace();
final String message = ex.getMessage();
yourActivity.runOnUiThread(new Runnable() {
public void run() {
// show toast
Toast.makeText(getApplicationContext, message, Toast.LENGTH_SHORT).show();
}
});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.