N Sharma
N Sharma

Reputation: 34497

When should I use BaseAdapter in Android?

I am working on android app in which I am using adapters to populate the data in a listview. I am confused where we should use BaseAdapter. I read many questions where it is written that we should use ArrayAdapter for arrays and arraylist that is ok and CursorAdapter in case of cursor.

I know BaseAdapter is the super class of ArrayAdapter and CursorAdapter. I have checked already this question What is the difference between ArrayAdapter , BaseAdapter and ListAdapter but it don't explain when we should use BaseAdapter.

When should I use BaseAdapter ?

Upvotes: 1

Views: 574

Answers (2)

ben75
ben75

Reputation: 28706

If your data is available in a Collection you can go with an ArrayAdapter. (use the addAll method to put your data in the adapter)

If your data is not in a Collection: then you can't and you must find another adapter that suits your needs. (typically: use a CursorAdapter when data comes from a database)

If you can't find any existing adapter working fine with your data structure/data source : you can write a subclass of BaseAdapter to support your own data structure.

If you plan to display your data in a ListView (this is a common use-case): then you must ensure that your adpter also implements ListAdapter (because the ListView needs a ListAdapter).

Note that ArrayAdapter and CursorAdapter implements ListAdapter.

Upvotes: 3

CommonsWare
CommonsWare

Reputation: 1006869

You should use it:

  • if your model data is not already in a data structure for which there is a concrete ListAdapter class, and

  • if you determine that creating a custom adapter will be better for the user, or perhaps less development work for you, than would be reorganizing your data structure

For example, suppose that you use JSONArray to parse a snippet of JSON. JSONArray does not implement the List interface, and therefore you cannot use it with ArrayAdapter. None of the other adapters match. Yet, you want to show this JSONArray in an AdapterView. In that case, your choices are:

  • roll through the data and convert it into an ArrayList, so you can use ArrayAdapter, or

  • create a custom subclass of BaseAdapter that can adapt a JSONArray (a JSONArrayAdapter)

  • stop using JSONArray and instead use something else for parsing your JSON, like Gson, which can populate a List directly, allowing you to use ArrayAdapter

Upvotes: 5

Related Questions