droid_user2476
droid_user2476

Reputation: 11

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.

Upvotes: 1

Views: 753

Answers (4)

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22637

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

Upvotes: 0

inazaruk
inazaruk

Reputation: 74780

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();

Upvotes: 0

jsp
jsp

Reputation: 2636

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

Upvotes: 1

Miguel Morales
Miguel Morales

Reputation: 1707

Do NOT mix UI code and network code. See: http://developer.android.com/resources/articles/painless-threading.html

Upvotes: 0

Related Questions