Adding items to the end of a ListView

冷暖自知 提交于 2019-12-08 12:18:32

问题


So, I'm doing this app where you have a ListView listing items that I get from a WebService and a Database. In this list I need a pull to refresh and load more itens when the user is near the end of the current list. Both the pull to refresh and the load more itens when near the end are working. But, the problem is when adding the items, insetead of adding a item to the top or end of the list, it just refreshes the whole list loading the new items and excluding the old ones. So, how can I add a item to the end or to the top of one ListView ?

Here some code to help:

@Override
    protected void onPostExecute(Boolean result) {
        Log.d("Async 4", "post");

        SampleAdapter adapter = new SampleAdapter(getActivity());


        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        for (int i = 0; i < 1; i++) {
            for (int w = 0; w < 1; w++) {
                for (int j = 0; j < 1; j++) {
                    int cont = 10;
                    cont++;
                    for (int k = 0; k < cont; k++) {
                        adapter.add(new SampleItem("" + title[k],"" + categoria_[i],"" + data_publicao[i], 1));
                        // Log.d("", "" + title[k]);
                        setListAdapter(adapter);
                    }
                }
            }
        }
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        pullToRefreshListView.onRefreshComplete();
    }

}

This code is where I try to add new items. I just call my async task that loads the data (from a WebService/Database), and the onPostExecute is suposed to add the newer items.

If more code from my project is needed, just ask and i'll put more. Thanks in advance.


回答1:


Your problem is that you are recreating the Adapter each time more items are fecthed.

adapter = new SampleAdapter(getActivity());
setListAdapter(adapter);

Move the creation of the adapter to your activity's onCreate method and make it a field of your activity class.

then instead of setting the adapter again in that for loop

just notify the adapter after the for loops after everything has been added;

adapter.notifyDataSetChanged()


来源:https://stackoverflow.com/questions/16401025/adding-items-to-the-end-of-a-listview

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