[Android Notes] Precautions for deleting an item in ArrayAdapter: Android arrayadapter
ArrayAdapter provides the remove Method to delete data from the data source and refresh the interface. The source code is as follows:
Public void remove (T object) {synchronized (mLock) {if (mOriginalValues! = Null) {mOriginalValues. remove (object) ;}else {mObjects. remove (object) ;}} if (mNotifyOnChange) notifyDataSetChanged (); // notify the observer}
The following is an example of ArrayAdapter usage:
mListView = (ListView) findViewById(R.id.lv);String[] data = {"aaaaaaaaaaaaaaaaaa","bbbbbbbbbbbbbbbb","aaaaaaaaaaaaaaaaaa","bbbbbbbbbbbbbbbb","aaaaaaaaaaaaaaaaaa","bbbbbbbbbbbbbbbb","aaaaaaaaaaaaaaaaaa","bbbbbbbbbbbbbbbb", };final List<String> d = new ArrayList<String>(Arrays.asList(data));mAdapter = new ArrayAdapter<String>(this, R.layout.item, R.id.tv,d);mListView.setAdapter(mAdapter);mListView.setOnItemClickListener(new OnItemClickListener(){@Overridepublic void onItemClick(int postion){mAdapter.remove(mAdapter.getItem(postion));}});
The above Code does not have any problems. You can delete entries. However, when we construct an ArrayAdapter
If the data source is not of the List type but an array type, an error is returned when you delete the data source.!
Cause:View the constructor of ArrayAdapter:
public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) { init(context, resource, textViewResourceId, Arrays.asList(objects));}
As you can see, it calls the Arrays. asList method to convert the array to the List type, but we know that this List cannot be added/removed. Therefore, the remove Method of ArrayAdapter reports an error. Therefore, when constructing an ArrayAdapter, you 'd better upload it to a List set (modifiable). You can also do this:
List<String> d = new ArrayList<String>(Arrays.asList(data));