Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaHow to Update RecyclerView Adapter Data in Android?

How to Update RecyclerView Adapter Data in Android?

RecyclerView is used in many android applications to display the list of data within android applications. We can dynamically add or remove data from our recycler view. For updating data in the RecyclerView, we have to use the Adapter class. Adapter handles all the data within our recycler view. In this article, we will take a look at How to Update Recycler View Adapter Data to update our Recycler View. A sample video is given below to get an idea about what we are going to do in this article.

Note: This Android article covered in both Java and Kotlin languages. 

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Working with the activity_main.xml file

Navigate to app > res > layout > activity_main.xml and add the below code to it. Comments are added in the code to get to know in detail. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/idRLContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
  
    <!--on below line we are creating our 
        edit text for adding new language-->
    <EditText
        android:id="@+id/idEdtAdd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:layout_toStartOf="@id/idBtnAdd"
        android:hint="Add item"
        android:textColorHint="@color/black" />
  
    <!--on below line we are creating a 
        button to add new language-->
    <Button
        android:id="@+id/idBtnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_margin="4dp"
        android:text="Add"
        android:textAllCaps="false" />
  
    <!--on below line we are creating a 
        recycler view for displaying data-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVItems"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/idEdtAdd"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
  
</RelativeLayout>


Step 3: Create a layout file for the item of RecyclerView

Navigate to app>res>layout>New>Layout Resource File and name it as lng_rv_item and add the below code to it. Comments are added in the code to get to know in detail. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="4dp"
    app:cardCornerRadius="4dp"
    app:cardElevation="9dp">
  
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
  
        <!--on below line we are creating a 
            text view for displaying a text-->
        <TextView
            android:id="@+id/idTVLngName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:padding="8dp"
            android:text="Language"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold" />
  
    </RelativeLayout>
  
</androidx.cardview.widget.CardView>


Step 4: Creating an Adapter class

Navigate to app>java>your app’s package name>Right click on it>New>Kotlin class and name it as LanguageRVAdapter and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
  
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
  
class LanguageRVAdapter(
    // on below line we are passing variables
    // as course list and context
    private var lngList: ArrayList<String>,
) : RecyclerView.Adapter<LanguageRVAdapter.ViewHolder>() {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): LanguageRVAdapter.ViewHolder {
        // this method is use to inflate the layout file 
        // which we have created for our recycler view.
        // on below line we are inflating our layout file.
        val itemView = LayoutInflater.from(parent.context).inflate(
            R.layout.lng_rv_item,
            parent, false
        )
        // at last we are returning our view holder 
        // class with our item View File.
        return LanguageRVAdapter.ViewHolder(itemView)
    }
  
    override fun onBindViewHolder(holder: LanguageRVAdapter.ViewHolder, position: Int) {
        // on below line we are setting text to our text view.
        holder.lngTV.text = lngList.get(position)
    }
  
    override fun getItemCount(): Int {
        // on below line we are 
        // returning the size of list.
        return lngList.size
    }
  
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // on below line we are initializing our text view.
        val lngTV: TextView = itemView.findViewById(R.id.idTVLngName)
    }
  
}


Java




package com.gtappdevelopers.googlemapsroutes.RecyclerView;
  
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.gtappdevelopers.googlemapsroutes.R;
import java.util.ArrayList;
  
public class LanguageRVAdapter extends RecyclerView.Adapter<LanguageRVAdapter.ViewHolder> {
    private ArrayList<String> languageRVModalArrayList;
  
    public LanguageRVAdapter(ArrayList<String> languageRVModalArrayList, Context context) {
        this.languageRVModalArrayList = languageRVModalArrayList;
    }
  
    @NonNull
    @Override
    public LanguageRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // this method is use to inflate the layout file 
        // which we have created for our recycler view.
        // on below line we are inflating our layout file.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lng_rv_item, parent, false);
          
        // at last we are returning our view holder
        // class with our item View File.
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull LanguageRVAdapter.ViewHolder holder, int position) {
        // on below line we are setting text to our text view.
        holder.lngTV.setText(languageRVModalArrayList.get(position));
    }
  
    @Override
    public int getItemCount() {
        return languageRVModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // on below line we are creating variable. 
        private TextView lngTV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // on below line we are initialing our variable. 
            lngTV = itemView.findViewById(R.id.idTVLngName);
        }
    }
}


Step 5: Working with the MainActivity file 

Navigate to app > java > your app’s package name > MainActivity file and add the code below. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
  
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
  
class MainActivity : AppCompatActivity() {
  
    // on below line we are creating variables.
    lateinit var lngRV: RecyclerView
    lateinit var addEdt: EditText
    lateinit var addBtn: Button
    lateinit var lngList: ArrayList<String>
    lateinit var lngRVAdapter: LanguageRVAdapter
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
          
        // on below line we are initializing our variables.
        lngRV = findViewById(R.id.idRVItems)
        addEdt = findViewById(R.id.idEdtAdd)
        addBtn = findViewById(R.id.idBtnAdd)
        lngList = ArrayList()
  
        // on below line we are 
        // adding data to our list.
        lngList.plusAssign("C++")
        lngList.plusAssign("C")
        lngList.plusAssign("Java")
          
        // on below line we are adding our list to our adapter.
        lngRVAdapter = LanguageRVAdapter(lngList = lngList)
  
        // on below line we are setting 
        // adapter to our recycler view.
        lngRV.adapter = lngRVAdapter
  
        // on below line we are adding click listener
        // for our add button.
        addBtn.setOnClickListener {
            // on below line we are calling add item method.
            addItem(addEdt.text.toString())
        }
        // on below line we are notifying adapter 
        // that data in adapter has been updated.
        lngRVAdapter.notifyDataSetChanged()
  
    }
  
    // on below line we are creating a 
    // new function to add item.
    private fun addItem(item: String) {
        // on below line we are checking
        // if item is empty or not.
        if (item.isNotEmpty()) {
            // on below line we are 
            // adding item to our list
            lngList.plusAssign(item)
            // on below line we are notifying 
            // adapter that data has updated.
            lngRVAdapter.notifyDataSetChanged()
        }
    }
}


Java




package com.gtappdevelopers.googlemapsroutes;
  
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.gtappdevelopers.googlemapsroutes.RecyclerView.LanguageRVAdapter;
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // on below line we are creating variables.
    private RecyclerView lngRV;
    private EditText addEdt;
    private Button addBtn;
    private ArrayList<String> lngList;
    private LanguageRVAdapter lngRVAdapter;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // on below line we are initializing our variables.
        lngRV = findViewById(R.id.idRVLanguages);
        addEdt = findViewById(R.id.idEdtAdd);
        addBtn = findViewById(R.id.idBtnAdd);
        lngList = new ArrayList<>();
  
        // on below line we are adding data to our list.
        lngList.add("C++");
        lngList.add("C");
        lngList.add("Java");
  
        // on below line we are adding our list to our adapter.
        lngRVAdapter = new LanguageRVAdapter(lngList);
  
        // on below line we are setting 
        // adapter to our recycler view.
        lngRV.setAdapter(lngRVAdapter);
  
        // on below line we are adding click listener for our add button.
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // on below line we are calling 
                // add item method.
                addItem(addEdt.getText.toString());
            }
        });
    }
  
    // on below line we are creating 
    // a new function to add item.
    private void addItem(String item) {
        // on below line we are checking
        // if item is empty or not.
        if (!item.isEmpty()) {
            // on below line we are adding
            // item to our list
            lngList.add(item);
            // on below line we are notifying 
            // adapter that data has updated.
            lngRVAdapter.notifyDataSetChanged();
        }
    }
  
}


Now run your application to see the output of it. 

Output:

RELATED ARTICLES

Most Popular

Recent Comments