开发者

Android Toast.makeText() not showing up

When the user presses a button, I'd like a small Toast.makeText() message show up saying something like Contacting server... while the app gets some information from my web server.

The problem is that Java's HttpClient.Execute() method is synchronous, so it blocks the Toast from showing up until the request has completed.

Is there way to have the Toast show up while the request is being sent?

e.g.

Toast.makeText(myContext, "Contacting server...", Toast.LENGTH_SHORT).sho开发者_如何学Pythonw();
String result = WebServer.Contact("www.mywebsite.com"); //A wrapper method
Toast.makeText(myContext, "Result: " + result, Toast.LENGTH_SHORT).show();

This code simply flashes the first Toast really fast after the request completes and then it shows the second Toast.


In order to show a Toast message you need to call show() on the Toast object from the UI thread. Therefore, put your Toast object where your UI thread runs (e.g. in AsyncTask's onPreExecute(), onPostExecute(), etc).

I'm assuming your connection is done in a separate thread.


As Pompe said, your HttpClient call should definitely on its own thread, and AsyncTask is a good way to go there. If you want to show the user something while it does its business, you might want to use a ProgressDialog (or some other Dialog) that you can than dismiss when the HttpClient call finishes. You can then show a Toast or whatever you want to display the result of the network call.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜