从远程服务器更新Listview数据

时间:2015-11-08 08:26:54

标签: android android-asynctask runnable

您好我正在尝试从远程服务器(php和mysql)更新我的listview数据,我使用Async任务方法从服务器调用数据,但我每隔2秒调用一次异步任务方法。我就是这样做的

    /**
     * The runnable method that is called every 2 seconds.
     */
      Runnable run= new Runnable() {
                public void run() {
                    new Comments(false).execute();
                    handler.postDelayed(this, 2000);
                }
            };
            runOnUiThread(run);



    /**
     * Async Task method for calling data from the remote servers
     */


    public class Comments extends AsyncTask<String, String, JSONArray> {

        public Comments(boolean showLoading) {
            super();
            // do stuff
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected JSONArray doInBackground(String... aids) {


            //This gets all the information unread from the server
            json = Function.Comments();

            return json;
        }

        @Override
        protected void onPostExecute(JSONArray json) {

            List<Application> apps = new ArrayList<Application>();

            if (json != null) {

                try {
                    for (int i = 0; i < json.length(); i++) {
                        JSONObject jsons = json.getJSONObject(i);

                        Application app = new Application();

                        //Values from the remote database
                        app.setMsgID(jsons.getString("msgID"));

                        apps.add(app);

                    }

                    ApplicationAdapter adapter = new ApplicationAdapter(context,apps);


                    ListView lView = (ListView) findViewById(R.id.lists);
                    lView.setAdapter(adapter);

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();

                }
            }
            else {
               //stuff

            }
        }

    }

这个逻辑工作正常,但我认为这不是在同一活动上更新列表视图最有效的方法,最有效的方法是什么?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您无需创建新适配器。只需使用新数据更新当前适配器即可。最简单的方法是清除所有数据并添加所有新数据:

ListView lView = (ListView) findViewById(R.id.lists);
ApplicationAdapter adapter = (ApplicationAdapter) lView.getAdapter();

adapter.clear();
adapter.addAll(apps);

您的用户界面会相应更新。