How to add, update and delete items in RecyclerView in android?

top banner

How to add, update and delete items in RecyclerView in android?

A RecyclerView that we have discussed in our previous lesson in details, is a powerful and flexible UI component that can be used in Android applications to display large sets of data efficiently. It is an improvement over the older ListView component, offering features like better performance and support for various layout managers.
Adding new items to a RecyclerView involves a few steps, and in this answer, we will go over each of them in detail. We will be using Kotlin programming language in this example.
Step 1: Define a data model The first step is to define a data model that represents the items you want to display in the RecyclerView. In this example, we will use a simple data model called “Item”, which has two properties: “name” and “description”.

data class Item(val name: String, val description: String) 

Step 2: Create a layout for the RecyclerView items Next, we need to create a layout that will be used to display each item in the RecyclerView. In this example, we will create a simple layout with a TextView for the name and another TextView for the description.

<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical">
 <TextView
 android:id="@+id/item_name"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:textSize="16sp" android:textStyle="bold" /> 
 <TextView
 android:id="@+id/item_description"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:textSize="14sp" />
</LinearLayout> 

Step 3: Create a ViewHolder A ViewHolder is a class that holds a reference to the views in the RecyclerView item layout. It is used to improve the performance of the RecyclerView by reducing the number of findViewById() calls. In this example, we will create a simple ViewHolder that holds references to the two TextViews in the item layout.

class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
 {
 val nameTextView: TextView = itemView.findViewById(R.id.item_name)
 val descriptionTextView: TextView = itemView.findViewById(R.id.item_description)
 } 

Step 4: Create an Adapter: An Adapter is responsible for creating and managing the RecyclerView items. In this example, we will create an Adapter that takes a list of items and inflates the item layout for each item.

class ItemAdapter(private val items: MutableList<Item>) : RecyclerView.Adapter<ItemViewHolder>()
 {
 override
 fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder
 {
 val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_layout, parent, false) return ItemViewHolder(view)
 }
 override
 fun onBindViewHolder(holder: ItemViewHolder, position: Int)
 {
 val item = items[position] holder.nameTextView.text = item.name holder.descriptionTextView.text = item.description
 }
 override
 fun getItemCount(): Int
 {
 return items.size
 }
 } 

To add new items in a RecyclerView

Step 5: Create a RecyclerView:
Now we can create a RecyclerView in our activity or fragment. In this example, we will create a RecyclerView in a fragment.

class ItemListFragment : Fragment()
 {
 private lateinit var recyclerView: RecyclerView
 private lateinit var adapter: ItemAdapter
 private var items = mutableListOf<Item>()
 override
 fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View?
 {
 val view = inflater.inflate(R.layout.fragment_item_list, container, false)
 recyclerView = view.findViewById(R.id.recycler_view)
 adapter = ItemAdapter(items)
 recyclerView.adapter = adapter
 recyclerView.layoutManager = LinearLayoutManager(requireContext())
 // add a button to add new items
 val addButton = view.findViewById<Button>(R.id.add_button)
 addButton.setOnClickListener
 {
 addItem()
 }
 return view
 }
 private fun addItem()
 {
 val name = "New Item" val description = "This is a new item" val item = Item(name, description) items.add(item) 
 adapter.notifyItemInserted(items.size - 1)
 }
 } 

We set the adapter and the layout manager of the RecyclerView in the onCreateView() method of the fragment. We also add a button that calls the addItem() method when clicked.

The addItem() method creates a new item with a default name and description, adds it to the list of items, and notifies the adapter of the new item using the notifyItemInserted() method. This method tells the adapter that a new item has been added and that it needs to update the RecyclerView to display the new item.

To update items in a RecyclerView in Android

Step 1: Update the data model We need to update the data model that holds the items to be displayed in the RecyclerView. In this example, let’s assume we want to update the “description” property of an item. We can simply update the corresponding property in the data model:

items[position].description = newDescription 

Step 2: Notify the adapter After updating the data model, we need to notify the adapter that the data has changed so that it can update the RecyclerView. We can do this using the notifyItemChanged() method of the adapter:

adapter.notifyItemChanged(position) 

This will cause the adapter to call the onBindViewHolder() method for the updated item, which will update the views in the corresponding ViewHolder.
Here’s the updated code for the addItem() method in the previous example, which updates the description of the first item in the list:

private fun updateItem()
 {
 if (items.isNotEmpty())
 {
 val position = 0
 val newItem = items[position].copy(description = "New description")
 items[position] = newItem adapter.notifyItemChanged(position)
 }
 } 

This code updates the description of the first item in the list to “New description”, and then notifies the adapter that the data has changed for that item.
That’s it! With these two steps, we can update items in a RecyclerView in Android.

To delete items in a RecyclerView in Android

Step 1: Remove the item from the data model We need to remove the item to be deleted from the data model that holds the items to be displayed in the RecyclerView. In this example, let’s assume we want to delete an item at a given position in the list. We can simply remove the item from the list:

items.removeAt(position) 

Step 2: Notify the adapter After removing the item from the data model, we need to notify the adapter that the data has changed so that it can update the RecyclerView. We can do this using the notifyItemRemoved() method of the adapter:

adapter.notifyItemRemoved(position) 

This will cause the adapter to remove the item from the RecyclerView and update the positions of the remaining items.
Here’s the updated code for the deleteItem() method in the previous example, which deletes the first item in the list:

private fun deleteItem()
 {
 if (items.isNotEmpty())
 {
 val position = 0
 items.removeAt(position)
 adapter.notifyItemRemoved(position)
 }
 } 

This code removes the first item in the list and then notifies the adapter that the data has changed for that item.
That’s it! With these two steps, we can delete items in a RecyclerView in Android.

Leave a Reply

Your email address will not be published. Required fields are marked *