I’m using ArrayAdapter to bind my data from my ArrayListto my ListView and i use an AlertDialogto insert data into my Arraylist. My problem is that i’m unable to refresh my ListView after the changes done.
Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config_hidden);
listView=(ListView) findViewById(R.id.hiddenList);
xmlFileManager=new XmlFileManager(this);
addNumber=(Button) findViewById(R.id.addNum);
addNumber.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
LayoutInflater factory = LayoutInflater.from(HiddenCall.this);
final View alertDialogView = factory.inflate(R.layout.add_number, null);
AlertDialog.Builder adb = new AlertDialog.Builder(HiddenCall.this);
adb.setView(alertDialogView);
adb.setTitle(R.string.dialog_title);
adb.setIcon(R.drawable.phone);
final AlertDialog alertDialog = adb.create();
adb.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
numberToAdd=(EditText) alertDialogView.findViewById(R.id.numberToAdd);
String number = numberToAdd.getText().toString();
if(number.length()>0){
xmlFileManager.addNumberToXml(number , HIDDEN_NUMBER_TYPE);
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, xmlFileManager.getHiddenNumbers());
adapter.setNotifyOnChange(true);
adapter.notifyDataSetChanged();
}
} });
adb.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
} });
adb.show();
}
});
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, xmlFileManager.getHiddenNumbers());
adapter.notifyDataSetChanged();
adapter.setNotifyOnChange(true);
listView.setAdapter(adapter);
}
You are instantiating a new adapter each time. What you have to do is put the line where you instantiate the adapter before the click listener, and in the click listener modify that adapter and call notifyDataSetChanged() on it. You of course have to add some setters to your adapter in order to modify the data.
Has to look similar to this: