How to raise a toast in AsyncTask, I am prompted to used the Looper
Solution 1
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
Solution 2
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();
}
});
Solution 3
You can also use runOnUiThread method to manipulate your UI from background threads.
Solution 4
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();
}
Solution 5
If you want to display the Toast from the background thread you'll have to call runOnUiThread from doInBackground. I don't believe there's another way.
Edit: I take that back. I think you can implement onProgressUpdate, which runs on the UI thread, to show the Toast and make calls to publishProgress from doInBackground.
Related videos on Youtube
Pentium10
Backend engineer, team leader, Google Developer Expert in Cloud, scalability, APIs, BigQuery, mentor, consultant. To contact: message me under my username at gm ail https://kodokmarton.com
Updated on July 09, 2022Comments
-
Pentium10 almost 2 years
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?
-
Pentium10 about 14 yearsI have to issue the Toast in the middle of the process, not in the end. What are my options?
-
Alex Volovoy about 14 yearsonProgressUpdate. It also runs on UI thread and Toast should be fine
-
demula almost 11 yearsworks for me. Just needed to call getActivivty().runOnUiThread(...)
-
necromancer over 9 years-1 downvoted because every other answer to this question is better than this one!
-
necromancer over 9 yearsoops, undownvoted because i did not notice the
onProgressUpdate
and only noticed theonPostExecute
-
Luís Gonçalves about 7 yearsThank you! This is exactly what I was looking for.