Mohamed Ali
Mohamed Ali

Reputation: 782

How to apply alphabetical sorting for names in a Recylcerview in android studios

I have a student tracking app that uses firebase for the backend. What I want to do now is to be able to sort the students by name once the Order Students button has been clicked. Right now I have a method that will sort the student by name using a Comparator attached to the button. I verified that it actually sorts by attaching println statements after the sorting is done. Now I am trying to figure out how to apply this logic to the RecyclerView in which the image of the student and names are being displayed. I will post the relevant code down below. Thank you all.

So the flow would look like this

Order Students Button Clicked -> Students are ordered by Alphabetical Order based on Name in RecyclerView

Edit I have posted the code for the RecyclerAdapter class below.

activity_view_students.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".ViewStudents">

    <Button
        android:id="@+id/addStudentButton"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:text="Add a Student"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="409dp"
        android:layout_height="729dp"
        android:layout_marginEnd="1dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" >

    </androidx.recyclerview.widget.RecyclerView>

    <Button
        android:id="@+id/orderStudents"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="orderStudents"
        android:text="Order Students"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

ViewStudents.class

public class ViewStudents extends AppCompatActivity {


    RecyclerView recyclerView;
    Button addStudent;


    private DatabaseReference myRef;

    public ArrayList<Students> students;
    private RecyclerAdapter recyclerAdapter;
    private Button orderStudents;

    private EditText mEditTextAge;
    private EditText mEditTextAssignment;

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

        recyclerView = findViewById(R.id.recyclerView);
        addStudent = findViewById(R.id.addStudentButton);
        mEditTextAge = findViewById(R.id.EditTextAge);
        mEditTextAssignment = findViewById(R.id.EditTextAssignment);
        orderStudents = findViewById(R.id.orderStudents);

        addStudent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ViewStudents.this, AddStudent.class));
            }
        });

        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        recyclerView.setHasFixedSize(true);

        myRef = FirebaseDatabase.getInstance().getReference();

        students = new ArrayList<>();

        ClearAll();

        GetDataFromFirebase();



    }
   // This method will make a call to firebase and get names and 
   // images of the students in the db
    private void GetDataFromFirebase() {
        Query query = myRef.child("student");

        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                ClearAll();
                for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    Students student = new Students();
                    if (snapshot.child("url").getValue() == null) {
                        student.setImageUrl(snapshot.child("imageUrl").getValue().toString());
                    }
                    else {
                        student.setImageUrl(snapshot.child("url").getValue().toString());

                    }
//                    student.setAge(mEditTextAge.getText().toString());
//                    student.setAssignment(mEditTextAssignment.getText().toString().trim());
                    student.setName(snapshot.child("name").getValue().toString());
                    students.add(student);
                }
                recyclerAdapter = new RecyclerAdapter(getApplicationContext(), students);
                recyclerView.setAdapter(recyclerAdapter);
                recyclerAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
    // will clear any pre-existing data 
    private void ClearAll() {
        if (students != null) {
            students.clear();

            if(recyclerAdapter != null) {
                recyclerAdapter.notifyDataSetChanged();
            }
        }
        students = new ArrayList<>();
    }

   // method to order students by name
    public void orderStudents(View view) {
        Intent orderIntent = new Intent(this, ViewStudents.class);
        startActivity(orderIntent);
        orderStudents.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Collections.sort(students, new Comparator<Students>() {
                    @Override
                    public int compare(Students o1, Students o2) {
                        return o1.name.compareTo(o2.name);
                    }
                });
            }
        });

        for(int i = 0; i < students.size(); i++){
            System.out.println("Students ==> " + students.get(i).getName());
        }

    }

RecycleAdapter.class

package com.example.studenttracker;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    private OnItemClickListener mListener;
    public interface OnItemClickListener {
        void onItemClick(int position);
    }
    public void setOnItemClickListener(OnItemClickListener listener) {
        mListener = listener;
    }
    private static final String Tag = "RecyclerView";
    private Context mContext;
    private ArrayList<Students> studentsArrayList;

    public RecyclerAdapter(Context mContext, ArrayList<Students> studentsArrayList) {
        this.mContext = mContext;
        this.studentsArrayList = studentsArrayList;
    }

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

    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        //TextView
        holder.textView.setText(studentsArrayList.get(position).getName());

        Glide.with(mContext).load(studentsArrayList.get(position).getImageUrl()).into(holder.imageView);

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView textView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            imageView = itemView.findViewById(R.id.imageView);
            textView = itemView.findViewById(R.id.textView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        int position = getAdapterPosition();
                        
                    }
                }
            });
        }
    }
}

Upvotes: 0

Views: 246

Answers (1)

Khantahr
Khantahr

Reputation: 8528

Change your RecyclerAdapter to extend ListAdapter, then you can have your orderStudents click method modify the list in the adapter, for example:

// method to order students by name
public void orderStudents(View view) {
    Intent orderIntent = new Intent(this, ViewStudents.class);
    startActivity(orderIntent);
    orderStudents.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            List<Students> l = recyclerAdapter.getCurrentList();
            Collections.sort(l, new Comparator<Students>() {
                @Override
                public int compare(Students o1, Students o2) {
                    return o1.name.compareTo(o2.name);
                }
            });
            recyclerAdapter.submitList( l );
        }
    });

Upvotes: 2

Related Questions