4

I have a ListAdapter as shown below:

setListAdapter(new ArrayAdapter<String>(DeleteMenu.this,             
                                  android.R.layout.simple_list_item_1, 
                                  classes));

I am trying to call notifyDataSetChanged() on it within an onListItemClick() function. I've tried a few different ways and looked at similar questions here on StackOverFlow but I still can't figure it out.

Can someone please help?

Edit: I should be more clear, I'm not getting an error, I simply don't know what to call the function notifyDataSetChanged() method on. Do I have to assign my ListAdapter to a variable and call it like var.notifyDataSetChanged()?

midhunhk
  • 5,560
  • 7
  • 52
  • 83
shanahobo86
  • 467
  • 2
  • 7
  • 23

3 Answers3

9

You should call notifyDataSetChanged on Adapter.

Adapter adapter = new Adapter();
ListView list = (ListView) findViewById(R.id.listview);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
Abdul Rahman
  • 2,097
  • 4
  • 28
  • 36
user1411084
  • 502
  • 1
  • 4
  • 11
  • Thanks but could you elaborate on this a little bit? – shanahobo86 Nov 17 '12 at 15:23
  • 3
    You call notifydatasetchanged on your adapter. You can't do that in your example cause you didn't give it a name to refer to it later. Does that make sense? – mango Nov 17 '12 at 19:00
  • 1
    There is no need to assign the adapter to a local variable. You are able to retrieve the adapter anywhere in a ListActivity/ListFragment by calling getListAdapter(). – Makibo Aug 09 '13 at 03:21
8

You can call the method notifyAdapterChanged() by getting a reference to the Adapter. You can either keep a local reference (like user1411084s answer), or retrieve it by calling:

getListAdapter()

Important to notice is that the interface ListAdapter doesn't provide the method notifyDataSetChanged(), so you should cast it to the type of the adapter you assigned earlier.

The result will look like this (able to call anywhere in your ListActivity/ListFragment:

((ArrayAdapter) getListAdapter()).notifyDataSetChanged();
Makibo
  • 1,679
  • 21
  • 31
  • 1
    getListAdapter() if your class extends http://developer.android.com/intl/ja/reference/android/app/ListFragment.html#getListAdapter() – Clocker Nov 29 '15 at 00:51
3
((BaseAdapter) listView.getAdapter()).notifyDataSetChanged(); 

See more info in this answer: https://stackoverflow.com/a/4198569/3994630

Pablo Cegarra
  • 20,955
  • 12
  • 92
  • 110