I have tasks completed by AsyncTask in background. At some point I need to issue a Toast that something is completed.
I've tried and I failed because
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
How can I do that?
You could wrap the Toast in runOnUIThread() but this isn't the best solution. You should set a boolean flag in the catch block when an error occurs, then display an appropriate Toast in onProgressUpdate() , onPostExecute() , or any of the other methods with UI access whenever the flag is true .
AsyncTask instances can only be used one time.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .
The basic methods used in an android AsyncTask class are defined below : doInBackground() : This method contains the code which needs to be executed in background. In this method we can send results multiple times to the UI thread by publishProgress() method.
onPostExecute - executes on UI thread or publishProgress()
; in your doinbackground and
protected void onProgressUpdate(Integer... progress) { }
http://developer.android.com/reference/android/os/AsyncTask.html
you can Toast inside doInBackground
add this code where you want to Toast appear
runOnUiThread(new Runnable() { public void run() { Toast.makeText(<your class name>.this, "Cool Ha?", Toast.LENGTH_SHORT).show(); } });
You can also use runOnUiThread method to manipulate your UI from background threads.
If you want to use Toast You should use this method : onProgressUpdate()
protected Integer doInBackground(Void...Params) {
int check_point = 1;
publishProgress(check_point);
return check_point;
}
protected void onProgressUpdate(Integer integers) {
if(integers == 1) {
Toast.makeText(classname.this, "Text", 0).show();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With