How to raise a toast in AsyncTask, I am prompted to used the Looper
Asked Answered
D

6

27

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?

Dvorak answered 14/5, 2010 at 21:13 Comment(0)
M
38

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

Mandibular answered 14/5, 2010 at 21:40 Comment(4)
I have to issue the Toast in the middle of the process, not in the end. What are my options?Dvorak
onProgressUpdate. It also runs on UI thread and Toast should be fineMandibular
-1 downvoted because every other answer to this question is better than this one!Weintraub
oops, undownvoted because i did not notice the onProgressUpdate and only noticed the onPostExecuteWeintraub
E
27

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();
    }
});
Exanimate answered 7/4, 2013 at 18:18 Comment(1)
Thank you! This is exactly what I was looking for.Edvard
F
20

You can also use runOnUiThread method to manipulate your UI from background threads.

Foxy answered 14/5, 2010 at 21:52 Comment(1)
works for me. Just needed to call getActivivty().runOnUiThread(...)Inkhorn
S
9

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(); 
}
Stylo answered 9/12, 2011 at 1:49 Comment(0)
P
1

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.

Precedency answered 14/5, 2010 at 22:48 Comment(0)
S
1

If you want to display the Toast in doInBackground, you can use it in the OnPostExecute method of AsyncTask.

protected void onPostExecute(String file_url) {    
   Toast.makeText(getApplicationContext(),"Your Message", Toast.LENGTH_LONG).show();

   pDialog.dismiss();//dismiss the progress dialouge
}
Socio answered 5/2, 2016 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.