0

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.

Carlos
  • 388
  • 2
  • 13
  • 33
  • Think of it as two separate things: the item list, and the adapter that connects to the `ListView`. You update the item list when new data arrives, and then you update the adapter with the newly edited list. The adapter you're using seems to have the data packaged inside it. In that case, you lose some control over the list, like where in the list your add() puts the new item. – Todd Sjolander May 06 '13 at 14:38

1 Answers1

2

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()
Pork 'n' Bunny
  • 6,740
  • 5
  • 25
  • 32
  • Yes, that did it. This is my first big app with lots of activities and fragments, its getting hard to spot such mistakes. Thanks a lot! – Carlos May 06 '13 at 14:57