Describe the role of an Adapter in Android development.

Instruction: Explain how an Adapter is used with Android UI components like ListView or RecyclerView.

Context: This question evaluates the candidate's understanding of foundational concepts in Android UI development. Candidates should explain that an `Adapter` acts as a bridge between a UI component and the data source, facilitating the display of data items within the UI component. They should also be able to describe the process of creating and setting up an Adapter, including overriding methods like `getView()` or `onBindViewHolder()` depending on the component used.

Updated

Official answer

An adapter translates an application's item model into the row representation required by a particular UI component. It does not inherently own networking or persistence. Keep slow data loading in a repository and give the adapter a suitable snapshot or paging stream.

For ListView, an implementation such as BaseAdapter supplies count, item, ID and getView. In getView, reuse a compatible non-null convertView; otherwise inflate the row using the parent for layout parameters without attaching it immediately. Cache child references and set all current row state, including clearing values absent in the new item. Merely extending the Adapter interface is not a complete ListView implementation.

For RecyclerView.Adapter, onCreateViewHolder builds a holder, onBindViewHolder displays a particular item, and getItemCount reports the current count. RecyclerView/LayoutManager coordinate reuse; onBindViewHolder is not itself a recycling mechanism. Assign the adapter and a suitable LayoutManager to the RecyclerView.

For example, a contacts row needs its current name, optional subtitle visibility, avatar placeholder and selected state on every full bind. If a holder moves from a selected contact with a subtitle to an unselected contact without one, both old states must be cleared. Updates should use an accurate diff or the corresponding notification contract.

At click time use the bound identity or valid current binding-adapter position, not a captured position that may have changed. Keep callbacks scoped to the screen/view lifetime. Test an empty list, row reuse, insertion before a row, deletion and a late image response.

Adapter contract, Adapter binding contract, RecyclerView roles

Related Questions