[Android Notes] Precautions for deleting an item in ArrayAdapter: Android arrayadapter

Source: Internet
Author: User

[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));







Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.