1

Have a frustrating problem with the adapter for Android ListView

I have this chunk of code:

@Override
public void onClick(View v, MotionEvent event, int position) {
    int value = dice.get(position).roll();
    adapter.notifyDataSetChanged();
    Toast.makeText(getApplicationContext(), "Click on "+position + " | Output: "+value, Toast.LENGTH_SHORT).show();
}

Where dice is an ArrayList of custom objects and adapter is an extension of ArrayAdapter. The Toast is always visible when clicking the view, but the ListView only updates sporadically. I can see no pattern to it; sometimes the view updates on click, sometimes after 2 or 3.

Any ideas? Thanks

Matt Balmer
  • 25
  • 1
  • 5
  • 1
    [This answer](http://stackoverflow.com/questions/3669325/notifydatasetchanged-example/5092426#5092426) might help... – neo108 Aug 07 '13 at 04:27
  • http://stackoverflow.com/questions/17292256/notifydatasetchanged-without-refreshing-the-ui/17292468#17292468. See this if it helps – Brijesh Thakur Aug 07 '13 at 04:28

4 Answers4

0

Try listview.invalidate() or listview.invalidateViews(), it may does the trick in your situation.

user2652394
  • 1,686
  • 1
  • 13
  • 15
0

listview.invalidate() might help.

Baby Groot
  • 4,637
  • 39
  • 52
  • 71
Sid87
  • 1
0
 @Override
public void onClick(View v, MotionEvent event, int position) {
    int value = dice.get(position).roll();
    dice.get(position).setValue(value); // Where setValue I hope is a method to set value of a item
    adapter.notifyDataSetChanged();
    Toast.makeText(getApplicationContext(), "Click on "+position + " | Output: "+value,     Toast.LENGTH_SHORT).show();
 }

Just to clarify, you have to change some value before call notifydatachanged, so you have to be sure to set new value to your dice item

Tizianoreica
  • 2,142
  • 3
  • 28
  • 43
  • .roll() changes the value of the object, and returns the result in addition. The adapter has a reference to `dice`, so it does change... sometimes. – Matt Balmer Aug 07 '13 at 18:41
0

I ended up having to reconstruct the ViewHolder for the pressed View inside of my custom ArrayAdapter, each time the onClick was triggered.

The source of the original frustration (why sometimes Android takes care of this automatically and sometimes it does not) remains uncertain to me.

Matt Balmer
  • 25
  • 1
  • 5