简体   繁体   中英

Unable to display Toast message when using with WebService

I need to display a message to the user "Communicating to the Server...Please wait for few seconds" when a call to a webservice is made. Currently I'm using Toast.makeText to display the message. For some reason, I don't see the message pop-up. But interestingly when I comment the web service method call, I see the Toast message.

Toast.makeText(this, "Communicating to the Server...Please wait for few seconds",      
                     Toast.LENGTH_SHORT).show();

//webservice code goes here...

Or any other alternative to satisfy this requirement is also fine.

Have you looked at using AysncTask . Using AsyncTask you can show a dialog with your message on onPreExecute() .

You can use AsyncTask to run your service and show Toast in onPreExecute .

Or you can use normal Thread but, you'll need to use Handler . Here is how:

class MyActivity extends Activity
{
    final Handler mHandler;
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(...);
        mHandler = new Handler();

        ...
    }

    void showToast(final String text)
    {
        mHandler.post(new Runnable()
        {               
            @Override
            public void run()
            {
                Toast.makeText(MyActivity.this, text, Toast.LENGTH_LONG).show();
            }
         });
    }

    class MyThread implements Runnable
    {
        @Override
        public void run()
        {
            showToast("your custom text");
            //your service code
        }
    }           
}

And here is how you start the thread:

Thread thread = new Thread(new MyThread());
thread.run();

the problem is that the UI thread is blocked as soon as you make the blocking web service call, so it never updates with the toast message. by the time it returns, the time for toast message has expired.

run your web service call in a thread, using AsyncTask, or just create a thread like,

new Thread(new Runnable() {
  public void run() {
    // WS call here

  }
}).start();

take care that if you create your own thread, you can only update the UI from the UI thread, so you'll need to use Handler.post() or sendMessage() to run the UI update on the UI thread.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM