开发者

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 t开发者_StackOverflow社区he 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().


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜