Search code examples
javaandroidandroid-alertdialog

Android - Refresh data in an AlertDialog?


So, if I create an AlertDialog like so:

AlertDialog.Builder b = new AlertDialog.Builder();
b.setItems(MyStringArray, MyListener);
b.create().show();

And then I want to update the items in the list, i.e. MyStringArray has changed to have more or fewer items. I can't seem to find a way to do this. So far, I've tried getting the ListView from the AlertDialog, but I can't seem to get .setAdapter to work. Is this the right approach, or is there a better way to do this?


Solution

  • I haven't tried this out myself, but from all the other apps I've built I'm pretty sure this will solve your problem.

    Instead of using setItems, try using the setAdapter() method and pass in an ArrayAdapter that has been initialized with the data from your Array of String. Then, when you know that the data has changed, you can use getListView() to get your View object and from there call getAdapter() so that now you're working directly with the dataset. You can clear it, and re-initialize it if you like, or just add / remove the items as you like. From the adapter object, if you call notifyDataSetChanged() it should trigger a re-draw using the new data set that you just supplied to the adapter.

    Hope that helps you out. Let me know if it doesn't.

    DSC