Skip to main content

How to sort a list in ascending order and Add header by the first letter in the RecyclerView in Android

Hello Forks ! Hope you are doing well. In this tutorial we will understand how to sort a list of data, it could be any data like bank names , places names etc. in ascending order with a header which grouped the same type of data under it. For example we have a list of banks data and we want to group all banks starting with 'A' character in single unit and so on. So without taking too much time  let's move to the coding part and understand how we can achieve this.

Step 1: Create a Model class Named Bank.java

public class Bank {
    private String name;

    public Bank(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Step 2: Sort the List of Banks with this Method

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public void sortBankList(List<Bank> bankList) {
    Collections.sort(bankList, new Comparator<Bank>() {
        @Override
        public int compare(Bank bank1, Bank bank2) {
            return bank1.getName().compareTo(bank2.getName());
        }
    });
}

Step 3: XML Layouts: activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EEEEF0"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

and Create item_bank.xml under layout section

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
   >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/section_header"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="20dp"
            android:background="#EEEEF0"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:text=""
            android:textStyle="bold"
            android:visibility="gone"/>

        <TextView
            android:id="@+id/bank_name"
            android:layout_width="match_parent"
            android:text=""
            android:paddingBottom="3dp"
            android:paddingTop="3dp"
            android:textSize="16sp"
            android:paddingLeft="20dp"
            android:background="#FFF"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</LinearLayout>

Step 4: Create RecyclerView Adapter: You need an adapter to manage the data for RecyclerView. This adapter will handle the grouping and display of bank names.

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 java.util.List;

public class BankAdapter extends RecyclerView.Adapter<BankAdapter.ViewHolder> {

    private List<Bank> bankList;

    public BankAdapter(List<Bank> bankList) {
        this.bankList = bankList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_bank, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Bank bank = bankList.get(position);
        holder.bankNameTextView.setText(bank.getName());
        // Set the first letter as a section header if it’s the first occurrence
        if (position == 0 || bank.getName().charAt(0) != bankList.get(position - 1).getName().charAt(0)) {
            holder.sectionHeaderTextView.setText(String.valueOf(bank.getName().charAt(0)));
            holder.sectionHeaderTextView.setVisibility(View.VISIBLE);
        } else {
            holder.sectionHeaderTextView.setVisibility(View.GONE);
        }
    }

    @Override
    public int getItemCount() {
        return bankList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView bankNameTextView;
        public TextView sectionHeaderTextView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            bankNameTextView = itemView.findViewById(R.id.bank_name);
            sectionHeaderTextView = itemView.findViewById(R.id.section_header);
        }
    }
}

the magical parts in this code is happening from this line 

if (position == 0 || bank.getName().charAt(0) != bankList.get(position - 1).getName().charAt(0)) {
            holder.sectionHeaderTextView.setText(String.valueOf(bank.getName().charAt(0)));
            holder.sectionHeaderTextView.setVisibility(View.VISIBLE);
        } else {
            holder.sectionHeaderTextView.setVisibility(View.GONE);
        }

It does nothing but check if position is 0 or compare first character of each position with another.if match then group into one else set its visibility to GONE if does match.

Step 5 : Setup RecyclerView in Activity:

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private BankAdapter bankAdapter;
    private List<Bank> bankList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        bankList = new ArrayList<>();
        // Add sample data
        bankList.add(new Bank("Axis Bank"));
        bankList.add(new Bank("Andhra Bank"));
        bankList.add(new Bank("Allahabad Bank"));
        bankList.add(new Bank("HDFC Bank"));
        bankList.add(new Bank("ICICI Bank"));
        bankList.add(new Bank("Indian Bank"));
        bankList.add(new Bank("State Bank of India"));
        bankList.add(new Bank("Bank of Baroda"));
        bankList.add(new Bank("Bank of Maharastra"));


        sortBankList(bankList);
        bankAdapter = new BankAdapter(bankList);
        recyclerView.setAdapter(bankAdapter);
    }
}

That it . Now compile and run your program and get the output.


This setup will sort the list of banks in ascending order and group them by the first letter in the RecyclerView. Thank You....Happy coding! 😊



Comments

Popular posts from this blog

How to Download Apk file from Url and Install Programmatically

In this post we learn about download apk file from server or website and then install it Programmatically in Phone. Sometimes we have to download external apk file from server and then install if downloading successfully finished.For this we use AsyncTask class  for background process. So here is Code Snippet for this task.Lets Start :- Before this we have to add these Permissions in Manifest.xml file : <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> DownloadNewVersion.java class DownloadNewVersion extends AsyncTask<String,Integer,Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); bar = new ProgressDialog(getActivity()); bar.setCancelable(false); bar.setMessage("Downl...

How to Implement Item Click Interface in Android?

In Android development, creating interactive lists is essential to most apps. Often, these lists include items that users can click on to trigger actions such as opening a new screen or displaying more information. In this tutorial, we’ll walk through how to implement an item click interface in Android using Java and XML. By the end of this guide, you’ll know how to create a RecyclerView with an item click listener that responds to user taps. This approach is widely used in modern Android development because RecyclerView is both flexible and efficient. Step 1: Set Up Your Android Project First, create a new Android project in Android Studio. Make sure to choose Java as the programming language. Step 2: Add Dependencies Make sure that you have the required dependencies for RecyclerView in your build.gradle file. If not, add them like this: dependencies {     implementation 'androidx.recyclerview:recyclerview:1.2.1' } Sync the project after adding the dependency. Step 3: Define ...

Working with Android 11 (Changes and Security Features)

 Hello everyone , I am here with new article which is hot topic nowadays "Android 11" .The stable version of Android.  Android 11 is the eleventh major release and 18th version of Android, the mobile operating system developed by the Open Handset Alliance led by Google. It was released on September 8, 2020.It is comes with many security features and other features as well . And it is now compulsory in play store  to upload new apps with API lavel 30 which is compatible with Android 11 and from November onwards old apps also have to update with API 30 .Some other guidelines you can check out from here . Play Store Guidelines So its clear that we have to update our apps with API level 30 .But Android 11 comes with some changes as well which we have to do in our projects. For example from Android developer site "Android 11 (API level 30) further enhances the platform, giving better protection to app and user data on external storage. ". Scoped storage enforcement: Apps...