如何在AsyncTask中刷新ListView?

时间:2013-07-25 06:48:04

标签: android android-listview android-asynctask

我正在使用AsyncTask并异步获取Twitter Feed以在listView中显示。它运行正常然后为了刷新列表视图,我将asyncTask调用放入Runnable的{​​{1}}以在特定时间间隔后加载它。在特定时间间隔后加载Feed但列表视图未更新。我在asyncTask中使用Run()但它不起作用。

这是我尝试的代码:

notifyDataSetChanged()

3 个答案:

答案 0 :(得分:0)

您是否尝试过移动此行:

list = (ListView) findViewById(R.id.list);

在你的onCreate方法中的setContentView之后?

答案 1 :(得分:0)

// related code adapter = new LazyAdapter(Twitter7FeedActivity.this, tweets);

取消注释onPostExecute()方法中的此代码。我想这可能对你有所帮助。感谢...

答案 2 :(得分:0)

您只需使用Handler即可完成问题中提到的工作。像这样:

public class Twitter7FeedActivity extends Activity {
LazyAdapter adapter;
ListView list;
JSONObject jsonObj = null;
JSONArray jsonArray = null;

@SuppressLint("SimpleDateFormat")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_twitter7_feed);
    callAsynchronousTask();
}

public void callAsynchronousTask() {
    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {

        ProgressDialog dialog;

        public void run() {
                    try {

                        //Show your dialog here
                        runOnUiThread(new Runnable() {
                            public void run() {
                                runnable.this.dialog = new ProgressDialog( Twitter7FeedActivity.this);
                                runnable.this.dialog.setMessage("Please wait");
                                runnable.this.dialog.show();
                            }

                         });

                        //Do your AsyncTask's doInBackground work here

                        //Update the UI with runOnUiThread or using the Ui threa handler
                        runOnUiThread(new Runnable() {
                            public void run() {
                                // related code adapter = new LazyAdapter(Twitter7FeedActivity.this, tweets);
                                list = (ListView) findViewById(R.id.list);
                                list.setAdapter(adapter); 
                                adapter.notifyDataSetChanged();
                            }

                         });

                         //Then post the thread to excecute after 50000 milliseconds.
                         handler.postDelayed(runnable, 50000);
                    } catch (Exception e)
                    { }
                }
    };
    handler.post(runnable);
    }
}

这样您就可以避免在AsyncTask内使用TimerTask