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

51,304

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.

Share:
51,304

Related videos on Youtube

Pentium10
Author by

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, 2022

Comments

  • Pentium10
    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
    Pentium10 about 14 years
    I have to issue the Toast in the middle of the process, not in the end. What are my options?
  • Alex Volovoy
    Alex Volovoy about 14 years
    onProgressUpdate. It also runs on UI thread and Toast should be fine
  • demula
    demula almost 11 years
    works for me. Just needed to call getActivivty().runOnUiThread(...)
  • necromancer
    necromancer over 9 years
    -1 downvoted because every other answer to this question is better than this one!
  • necromancer
    necromancer over 9 years
    oops, undownvoted because i did not notice the onProgressUpdate and only noticed the onPostExecute
  • Luís Gonçalves
    Luís Gonçalves about 7 years
    Thank you! This is exactly what I was looking for.