Skip to content Skip to sidebar Skip to footer

How Can I Call Toast.maketext() According To Result Of Asynctask In Protected String Doinbackground Method?

I fetched data from the database in AsyncTask and if it is null, I want to Toast a warning text. I tried in AsyncTask but i learned that it isn't called in a worker thread. Here is

Solution 1:

doInbackground is invoked on a background thread. So you cannot update ui on a different thread other than the ui thread.

You can return the result in doInbackground Based on the result update ui in onPostExecute or use runOnUithread which is a method of activity class.

runOnUiThread(newRunnable() {

                    @Overridepublicvoidrun() {
                        // toast here
                    }
                });

Or

protectedStringdoInBackground(Boolean... params) {
// other codereturn"status"
} 
@OverrideprotectedvoidonPostExecute(String result) {
super.onPostExecute(result);
    Toast.makeText(getApplicationContext(),"My status is"+result,Toast.LENGTH_SHORT).show(); 
}

Edit

As suggested by @codeMagic move you startActivity also to onPostExecute. Also you do not want to cancel the asynctask run when you still have code to run

Solution 2:

if you wanted to do this use handler so code will be

declare Handler handler = new Handler(); as member varible in activity class and use following for displaying tost

handler.post( new Runnable(){
   publicvoidrun(){
Toast.makeText(getApplicationContext(), "You entered wrong values.",Toast.LENGTH_LONG).show(); 
       }
});

Solution 3:

You can pass the Handler of the main thread to the AsyncTask, and then use the Handler to schedule a task that post a toast message. Here is the java doc for the Handler class:

http://developer.android.com/reference/android/os/Handler.html

Basically you should create that object in the main/UI thread (and it will be automatically bound to the Looper of the main/UI thread). Then you would pass it to your AsyncTask. Then when you need to showing the message you use Handler.post(Runnable) method

Solution 4:

The Toast messages must be called in the main/UI thread. The ways you can solve this are:

  • Put your Toast inside the onPostExecute of your AsyncTask
  • Create a wrapper of normal Toast that will run on the UI thread using:

Example:

activity.runOnUiThread(newRunnable() {

@Overridepublicvoidrun() {
     Toast.make...
}
});

Post a Comment for "How Can I Call Toast.maketext() According To Result Of Asynctask In Protected String Doinbackground Method?"