Reputation: 16710
I am trying to implement a way to remove items from a ListView when text is added to an EditText, sort of like an auto complete.
I have created the following ArrayAdapter to test simply:
mListViewItem; // My ListView
mEditTextItem; // My EditText
String[] arr = new String[]{"One", "Two", "Three", "Four", "Five"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item_medication, arr);
mListViewItem.setAdapter(adapter);
Now, I added an event handler to handle text changes. For now, all I want to do is remove items that do not contain the input of the EditText. For this example, if I type "O", then items 'Three' and 'Five' should be removed. I have tried this:
mEditTextItem.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
for(int i = 0; i < adapter.getCount(); i++){
if(!adapter.getItem(i).contains(s)){
adapter.remove(adapter.getItem(i));
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
But I don't know how to code the 'remove' function to remove necessary items, as this gives me an UnsupportedOperationException
.
Upvotes: 0
Views: 534
Reputation: 87064
But I don't know how to code the 'remove' function to remove necessary items, as this gives me an UnsupportedOperationException
If you pass an array as the data for an ArrayAdapter
that array will be transformed into an unchangeable list(this mean you can't change the size of the list by adding or removing items from it). This is what the adapter is trying to do when using remove()
and it obviously fails with that exception.
The most simply solution is to use a normal list(like ArrayList
) with the data instead of that array:
String[] arr = new String[]{"One", "Two", "Three", "Four", "Five"};
List<String> data = new ArrayList<String>();
for (String item : arr) {
data.add(item);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item_medication, data);
mListViewItem.setAdapter(adapter);
Upvotes: 2