Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 680
Pentium10 Avatar asked May 14 '10 21:05

Pentium10


People also ask

How do I show toast in AsyncTask?

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 .

How many times an instance of AsyncTask can be executed?

AsyncTask instances can only be used one time.

In which thread AsyncTask function will execute?

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 .

What is the method name for executing in background thread for AsyncTask approach?

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.


4 Answers

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

like image 187
Alex Volovoy Avatar answered Sep 27 '22 16:09

Alex Volovoy


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();     } }); 
like image 33
Noob Avatar answered Sep 27 '22 18:09

Noob


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

like image 44
Alexander Oleynikov Avatar answered Sep 27 '22 16:09

Alexander Oleynikov


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(); 
}
like image 44
Korean Avatar answered Sep 27 '22 16:09

Korean