【问题标题】:How to make android Listview update every 10 sec?如何让 android Listview 每 10 秒更新一次?
【发布时间】:2016-05-23 16:02:49
【问题描述】:

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

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();
    }
}

【问题讨论】:

  • 如果你只想在 10 秒内更新它而不管服务器发送的数据如何,使用 Timer.scheduleAtFixedRate()
  • 如何使用请告诉我我是android新手
  • 您也可以使用 CountDownTimer。启动定时器10秒,将更新后的arrayList传给Adapter,在adapter上执行notifySetDataChange。

标签: android listview android-studio refresh


【解决方案1】:

如何以固定的间隔重复一段代码,本例更新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();
   }
}

代码仅作为示例。

【讨论】:

  • 想知道它们是什么?
猜你喜欢
  • 1970-01-01
  • 2022-11-26
  • 2022-09-22
  • 1970-01-01
  • 1970-01-01
  • 2013-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多