Update UI Asynchronously in Android

女生的网名这么多〃 提交于 2019-12-02 07:48:06
codeMagic

Here is an example of an AsyncTask

public class TalkToServer extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);

}

@Override
protected String doInBackground(String... params) {
//do your work here
    return something;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
       // do something with data here-display it or send to mainactivity
}

Then you can access by calling

TalksToServer varName = new TalkToServer(); //pass parameters if you need to the constructor
varName.execute();

Async Docs Progress Dialog Example

You don't want to do network stuff or call sleep on the UI thread. If it is an inner class then you will have access to your member variables of the outer class. Otherwise, create a contructor in the AsyncTask class to pass context if you want to update from onPostExecute or other methods besids doInBackground().

As everyone has mentioned, you're making network calls in the UI thread and performing Thread.Sleep() which freezes your UI.

I'd try something like this AsyncHttpClient class, it has all the functionality you need, you'll have to perform your UI updates in the callback.

http://loopj.com/android-async-http/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!