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?

Pentium10
  • 204,586
  • 122
  • 423
  • 502

6 Answers6

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

Alex Volovoy
  • 67,778
  • 13
  • 73
  • 54
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();
    }
});
Noob
  • 2,857
  • 6
  • 33
  • 47
20

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

Alexander Oleynikov
  • 19,190
  • 11
  • 37
  • 51
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(); 
}
Korean
  • 91
  • 1
  • 1
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.

Brandon O'Rourke
  • 24,165
  • 16
  • 57
  • 58
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
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Nilay
  • 79
  • 9