0

its my code. What i doing wrong? I would like to display descending results in recyclerview.

TableInfo.TABLE_COLUMN_MESSAGE = "points"

override fun onBindViewHolder(p0: MojViewHolder, p1: Int) {

    val wynikwynik = p0.view.textViewWynik
    val wynikuser = p0.view.textView_user


    val cursor = db.query(TableInfo.TABLE_NAME, null, BaseColumns._ID + "=?", arrayOf(p0.adapterPosition.plus(1).toString()), null, null, TableInfo.TABLE_COLUMN_MESSAGE +" DESC")



    if (cursor.moveToFirst()){

        wynikwynik.text=cursor.getString(1).toString()
        wynikuser.text=cursor.getString(2).toString()

    }


    cursor.close()

}
rafa
  • 1,319
  • 8
  • 20
Jayeson
  • 1
  • 3
  • Possible duplicate of [How to sort RecyclerView item in android](https://stackoverflow.com/questions/45790363/how-to-sort-recyclerview-item-in-android) – Martin Zeitler Dec 01 '18 at 07:03

3 Answers3

2

First of all you should separate the view of your Business Logic, I want to say you shouldn't do a db request within of recyclerView, the best way is pass an val of data in your recyclerView, this data is the info for your recyclerView lList, if you make a db request inside of your ViewHolder you are making a request in every row of your List and this is a problem.

Check this information of the work of a recycler view: https://developer.android.com/guide/topics/ui/layout/recyclerview

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

This statement fetches only 1 row, because as I understand BaseColumns._ID is the primary key of the table.
So you pass p0.adapterPosition.plus(1).toString() as an argument to the statement and the query() method fetches the row with this id.
So there is no sorting for only 1 row!

If you want to fetch all the rows of the table sorted descending, you must execute this statement:

val cursor = db.query(TableInfo.TABLE_NAME, null, null, null, null, null, TableInfo.TABLE_COLUMN_MESSAGE + " DESC")

or even better use rawQuery():

val cursor = db.rawQuery("SELECT * FROM " + TableInfo.TABLE_NAME + " ORDER BY " + TableInfo.TABLE_COLUMN_MESSAGE + " DESC", null)
forpas
  • 160,666
  • 10
  • 38
  • 76
0

hard-coding sort-order DESC prevents any alternate (remote or database) sorting ...

at least unless the adapter items not implement Comparable<T> (for local sorting).

to query the database onBindViewHolder() is just wrong.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216