Codist
Codist

Reputation: 769

How to show the data that retrieved from the Firestore in reverse order in a recyclerView in Kotlin Android?

I have the following code to show the data in recyclerView that I retrieve from firestore. What I am trying to do is, show the data in recyclerView in the reverse order of the data I get from Firestore.

    fun populateOrdersListInUI(ordersList: ArrayList<Order>) {

    hideProgressDialog()

    if (ordersList.size > 0) {

        rv_my_order_items.visibility = View.VISIBLE
        tv_no_orders_found.visibility = View.GONE

        rv_my_order_items.layoutManager = LinearLayoutManager(activity)
        rv_my_order_items.setHasFixedSize(true)

        val myOrdersAdapter = MyOrdersListAdapter(requireActivity(), ordersList)
        rv_my_order_items.adapter = myOrdersAdapter
    } else {
        rv_my_order_items.visibility = View.GONE
        tv_no_orders_found.visibility = View.VISIBLE
    }
}

Thank you.

Eidt:

enter image description here

Edit: Added xml code.

    <?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"
    android:background="@color/colorOffWhite"
    tools:context=".ui.fragments.OrdersFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_my_order_items"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

Upvotes: 0

Views: 284

Answers (2)

Dominik Wuttke
Dominik Wuttke

Reputation: 555

Just create a reversed Arraylist before you submit it to your adapter.

val reversedArray = ArrayList(ordersList.reversed())
val myOrdersAdapter = MyOrdersListAdapter(requireActivity(), reversedArray)

You can also reverse the ArrayList without creating a new one

ordersList.reverse()
val myOrdersAdapter = MyOrdersListAdapter(requireActivity(), ordersList)

Upvotes: 1

Rahul Rawat
Rahul Rawat

Reputation: 380

Try using this constructor of LinearLayoutManager while setting reverseLayout to true like

rv_my_order_items.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, true)

if it is a vertical and HORIZONTAL for horizontal orientation. This way you won't have to keep on reversing and adding list if you choose to add data to your arraylist

Upvotes: 1

Related Questions