Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 560
Paul Avatar asked Jan 16 '12 06:01

Paul


1 Answers

If you are like me and you would like to use default adapter for example for multichoice items, then there is also a way.

Just as with any other adapter just update the string array object, get adapter from the dialog instance, cast it to appropriate adapter and invalidate it.

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

// Later when you need to update
MyStringArray[0] = "puf";
ListView list = instance.getListView();
// Now according to whether you used cursor or array for supplying items to the builder
// you have to cast adapter to either CursorAdapter or ArrayAdapter
ArrayAdapter adapter = (ArrayAdapter)list.getAdapter();
adapter.notifyDataSetChanged();

You can find out more here.

like image 162
Martin Rajniak Avatar answered Oct 13 '22 00:10

Martin Rajniak