如何每10秒更新一次android Listview更新?

时间:2016-05-23 16:02:50

标签: android listview android-studio refresh

我有一个列表视图数据来自服务器并显示在列表视图中。我想每10秒刷新一次listview我怎么能这样做这是我的列表视图代码。

protected void showList() {
    try {
        JSONObject jsonObj = new JSONObject(myJSON);
        peoples = jsonObj.getJSONArray(TAG_RESULTS);

        for (int i = 0; i < peoples.length(); i++) {
            JSONObject c = peoples.getJSONObject(i);

            String data = c.getString(TAG_DATA);
            final String dataaaa = rcdata.getText().toString().trim();
            HashMap<String, String> user_data = new HashMap<String, String>();
            user_data.put(TAG_DATA, data);
            personList.add(user_data);
        }

        ListAdapter adapter = new SimpleAdapter(
                DataSendActivity.this, personList, R.layout.layout_chat,
                new String[]{TAG_DATA},
                new int[]{R.id.data}

        );

        list.setAdapter(adapter);

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

如何在固定时间间隔内重复一段代码,在本例中为update listview

//instance variable for adapter
ListAdapter adapter;
//instance variable for timer
Timer timer;

//create the listview, adapter and set the adapter
public void showList(){
    //method code;
    adapter=//call adapter constructor
    listView.setSetAdapter(adapter);

    //create a handler to update the adapter
    final Hanlder handler=new Handler(){
          //run your listview update command here. Possibly;
          adapter.notifyDataSetChanged();
          //or else create a new adapter
          adapter=new ListAdapter(//parameters);
          listView.setAdapter(adapter);
    }
    //create timer and the scheduled task
    //this will run in every 10 seconds. Make sure to stop it when you dont
    //want it any more
    timer=new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
         @Override
         public void run() {
              handler.obtainMessage().sendToTarget();
         }
    }, 0, 10000);
}

//if you want to stop the timer on onDestroy()
@Override
public void onDestroy(){ 
   super.onDestroy();
   if(timer!=null){
      timer.cancel();
   }
}

代码仅作为示例。