How to make ListView to refresh after every 5 sec when data come from a server

笑着哭i 提交于 2020-02-06 07:28:29

问题


I have ListView which have data . Data come from server and I want the ListView to update after every 5 sec. How to do this? I am new to android development. Please help me. Here is my code...

    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:


Use a Handler and its postDelayed method to invalidate the list's adapter as follows:

final Handler handler = new Handler();
handler.postDelayed( new Runnable() {

    @Override
    public void run() {
        adapter.notifyDataSetChanged();
        handler.postDelayed( this, 5000 );
    }
}, 5000 );

You must only update UI in the main (UI) thread.




回答2:


you can see this question and comment How to refresh/Update Serialize Java Object in sharedPreferences. the user want the same. however it is good to use loader with service for that kind of problem calling asyncTask within minute is not good. also theres is a sample project you can check this https://github.com/Michenux/YourAppIdea also available in playstore which check for data changes from server.



来源:https://stackoverflow.com/questions/37404521/how-to-make-listview-to-refresh-after-every-5-sec-when-data-come-from-a-server

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