Monday, May 19, 2014

[android-developers] Re: ListView getCount is wrong - how do I reset it?

It's public and static because the method in the ListActivity that calls it is static.   So if it wasn't static it would generate a compile-time error that a static method can't refence a non-static object.   The ListActivity method is static is that way because that's how the original program was architected and I don't have the authority to change the architecture.

But why does it matter?    Why can't the size of a ListView be reset if it's static?

On Saturday, May 17, 2014 4:11:48 AM UTC-4, Doug wrote:

On Friday, May 16, 2014 11:58:17 AM UTC-7, plnelson wrote:
...In MyListActivity, which is a ListActivity . . .

public static ListView lv;   // my ListView in the code

Why is this public and static?
...the data source is an ArrayList called listItems. The first time around it has 12 items in it; later I clear it and add in 6 items. (see below)

public static ArrayList<String>listItems=new ArrayList<String>();

Why is this public and static?
... in my adapter, which is a BaseAdapter, my override of getCount() looks like this. After shrinking listItems to 6 it correctly returns 6.

public int getCount() {
    return listItems.size();

... To shrink my dataset to 6 I first do a

lv.invalidate();   // my (failed) attempt to get lv to reset its count

Invalidate doesn't do what you think it does.  That has to do with the rendering of the view on screen, not the contents of the adapter that the ListView knows about.
... and then add in the 6 new items. After adding each item to listItems I do a notifyDataSetChanged() on the adapter. What I've noticed is that if I do an lv.getCount it returns 12, i.e., the value it was before doing the listItems.clear() and invalidate(). Why does the ListView still think it's 12? How do I reset it? Is that why the adapter thinks it's too big?

Try setting a new (non-public, non-static) adapter into the ListView instead.

Never change the contents of the data in an adapter after you've given it to the ListView.  Make a deep copy of the data before sending it if you have to.


You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at
You received this message because you are subscribed to the Google Groups "Android Developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
For more options, visit

No comments:

Post a Comment