Kotlin, recyclerview adapter how to sort results f

2019-09-01 02:53发布

问题:

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()

}

回答1:

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



回答2:

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.



回答3:

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)