Vitor Ferreira
Vitor Ferreira

Reputation: 1095

FirebaseRecyclerPagingAdapter - sort list by date

In my app I want to display a list of news that are saved in the Realtime Database. Each news item has a timestamp in milliseconds to indicate the date of the news. I want to display the latest news first on RecyclerView using FirebaseRecyclerPagingAdapter. How to do this?

    val baseQuery: Query = FirebaseDatabase.getInstance().reference.child("news")

    val config = PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPrefetchDistance(2)
            .setPageSize(3)
            .build()

   
    val options: DatabasePagingOptions<News> = DatabasePagingOptions.Builder<News>()
            .setLifecycleOwner(this)
            .setQuery(baseQuery, config, News::class.java)
            .build()


    val adapter: FirebaseRecyclerPagingAdapter<News, ViewHolder> = object : FirebaseRecyclerPagingAdapter<News, ViewHolder>(options) {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val item = LayoutInflater.from(parent.context).inflate(R.layout.item_news_1, parent, false)
            return ViewHolder(item)
        }

        override fun onBindViewHolder(viewHolder: ViewHolder, position: Int, model: News) {
            viewHolder.bind(model)
        }

        override fun onLoadingStateChanged(state: LoadingState) {

        }
    }

database:

"news" : {
      "-MXJ0Fbmvewl3zZ6-Ugn" : {
        "timestamp" : 1617108780000,
        "description" : "A Red Bull tem a expectativa de chegar ainda melhor ao GP da Emilia Romagna de Fórmula 1, disputado no próximo dia 18 de abril, em Ímola. Após ver o holandês Max Verstappen ser batido pela Mercedes do britânico Lewis Hamilton no GP do Bahrein, o time de energéticos pretende dar um 'salto' a fim de garantir a vitória na segunda etapa da temporada 2021 da categoria máxima do ...Continue lendo",
        "id" : "-MXJ0Fbmvewl3zZ6-Ugn",
        "thumb" : "https://cdn-1.motorsport.com/images/amp/YpNW51X0/s6/formula-1-bahrain-gp-2021-max--2.jpg",
        "title" : "F1: Red Bull deve estar ainda melhor na etapa de Ímola; saiba mais",
        "url" : "http://motorsport.uol.com.br/f1/news/f1-red-bull-deve-estar-ainda-melhor-em-imola-entenda-os-detalhes/5991023/?utm_source=RSS&utm_medium=referral&utm_campaign=RSS-ALL&utm_term=News&utm_content=br"
      },
      "-MXJ0LxzjUjfGFDvamKE" : {
        "timestamp" : 1617118680000,
        "description" : "As mudanças nas regras da Fórmula 1 para reduzir o downforce nos carros provaram ser uma grande dor de cabeça para as equipes no inverno europeu - e se tornaram um grande ponto de discussão no Bahrein no último final de semana. As mudanças no assoalho, dutos de freio e difusor visavam originalmente reduzir o downforce em 10%, embora as indicações sugiram que as escuderias já ...Continue lendo",
        "id" : "-MXJ0LxzjUjfGFDvamKE",
        "thumb" : "https://cdn-1.motorsport.com/images/amp/YBeqJen2/s6/lance-stroll-aston-martin-amr2.jpg",
        "title" : "Análise técnica: entenda como as equipes de F1 responderam ao desafio do assoalho de 2021",
        "url" : "http://motorsport.uol.com.br/f1/news/analise-tecnica-entenda-como-as-equipes-de-f1-responderam-ao-desafio-do-assoalho-de-2021/5992503/?utm_source=RSS&utm_medium=referral&utm_campaign=RSS-ALL&utm_term=News&utm_content=br"
      },
    }

Upvotes: 1

Views: 192

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598775

You can use a query to order the items by their timestamp value

val baseQuery: Query = FirebaseDatabase.getInstance().reference.child("news")
val orderedQuery: Query = baseQuery.orderByChild("timestamp")

This will give you the items in ascending order, so you will have to reverse them in your application code.

If you don't want to do that, consider storing an inverted timestamp value in your data:

"news" : {
  "-MXJ0Fbmvewl3zZ6-Ugn" : {
    "timestamp" : 1617108780000,
    "inverted_timestamp" : -1617108780000,
    "description" : "A Red Bull tem a ......Continue lendo",
    "id" : "-MXJ0Fbmvewl3zZ6-Ugn",
    "thumb" : "https://cdn-1.motorsport.com/images/amp/YpNW51X0/s6/formula-1-bahrain-gp-2021-max--2.jpg",
    "title" : "F1: Red Bull deve estar ainda melhor na etapa de Ímola; saiba mais",
    "url" : "http://motorsport.uol.com.br/f1/news/f1-red-bull-deve-estar-ainda-melhor-em-imola-entenda-os-detalhes/5991023/?utm_source=RSS&utm_medium=referral&utm_campaign=RSS-ALL&utm_term=News&utm_content=br"
  },
  "-MXJ0LxzjUjfGFDvamKE" : {
    "timestamp" : 1617118680000,
    "inverted_timestamp" : -1617118680000,
    "description" : "As mudanças nas ...Continue lendo",
    "id" : "-MXJ0LxzjUjfGFDvamKE",
    "thumb" : "https://cdn-1.motorsport.com/images/amp/YBeqJen2/s6/lance-stroll-aston-martin-amr2.jpg",
    "title" : "Análise técnica: entenda como as equipes de F1 responderam ao desafio do assoalho de 2021",
    "url" : "http://motorsport.uol.com.br/f1/news/analise-tecnica-entenda-como-as-equipes-de-f1-responderam-ao-desafio-do-assoalho-de-2021/5992503/?utm_source=RSS&utm_medium=referral&utm_campaign=RSS-ALL&utm_term=News&utm_content=br"
  },
}

With the above data structure, you can then get them items in descending order with:

val orderedQuery: Query = baseQuery.orderByChild("inverted_timestamp")

You can then pass the orderedQuery to the adapter, to see the items based on their descending timestamp.

Upvotes: 2

Related Questions