Kotlin, recyclerview adapter how to sort results from query by DESC

时光总嘲笑我的痴心妄想 提交于 2019-12-11 15:37:55

问题


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)


来源:https://stackoverflow.com/questions/53561869/kotlin-recyclerview-adapter-how-to-sort-results-from-query-by-desc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!