Search code examples
androidandroid-adapterview

Which is the correct way to add item into ArrayAdapter


Consider the following code.

List<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, resource, textViewResourceId, list);

// Method 1 : Add an item.
adapter.add("ITEM1");

// Method 2 : Add an item
list.add("ITEM2");

I was wondering, which is the correct way to add item into ArrayAdapter? As seems to me, both methods just work fine.


Solution

  • Method 1 updates the associated AdapterView, if you have already attached the ArrayAdapter to the AdapterView. Method 2 does not, requiring you to call notifyDataSetChanged() on the ArrayAdapter.

    Typically, you populate the ArrayList before creating the ArrayAdapter, then use Method 1 to add new entries dynamically later on (e.g., based on user data entry).