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...

Auto read OTP using SMS User Consent API in Android

Some times ago Google Play restricts the use of high risk or sensitive permissions, including the SMS or Call Log permission groups. It means you have to justify why you are taking SMS or other high risk or sensitive permissions for your application .For this you may be required to complete the Permissions Declaration Form and receive approval from Google Play. Before this every app even who does not have any purpose for taking SMS or other high sensitive permissions in their app ,They was taking these permissions from users and this is a kind of security beach.  For solution of this problem Google introduce SMS User Consent API . The SMS User Consent API complements the SMS Retriever API by allowing an app to prompt the user to grant access to the content of a single SMS message. When a user gives consent, the app will then have access to the entire message body to automatically complete SMS verification. If your appeal for SMS permission is rejected by Google team you can u...

How to open pdf file url using webview in Android

 Sometimes we have requirement of showing pdf file in our Android Application. Although there are many third party gradle dependencies available online by which you can show your pdf file easily but one of the major drawback of using these libraries are they will increase you apk size .In some cases they will increase apk size upto ~14 MB. Alternatively you can access and show pdf file using assets and from storage options. This can take less size than any third party library. Here we use pdf using url and if you directly open your pdf file url in webview you will get no result because it will start downoad if you open this link in any web browser.  So in this article we will learn how we can open our pdf url using webview and without using any third party library. So lets Start step by Step:- Lets Suppose you have a pdf file url something like   http://yourwebsite.com/files/mydocumentfile.pdf Step 1: So we you this pdf file url to embed in our webview .First of all you h...