Search code examples
androidandroid-studioandroid-room

Problems with Room on Android Studio


So, i want to create a button on Android Studio that updates my list in a sorting order, Ascending, etc., but i've been running in to some problems with the code and i can wrap my head around it. When i click the button nothing happends, it doesn't sort my list at all

Using Room Database FrameWork from Andriod Studio.

This is what i using to do the sorting:


 //'Produto' is the list, 'nome' is a element on that list that i want to sort
 @Entity 
 @Parcelize 
 data class Produto(
 @PrimaryKey(autoGenerate = true)
 val id: Long,      
 val nome: String)


@Query("SELECT * FROM Produto") 
    fun buscaTodos() : List<Produto>

//This is the code that i use to do the sorting
@Query("SELECT * FROM Produto ORDER BY nome ASC")
    fun getAllSortedByName(): List<Produto>

This is the code to i'm using to do the sorting after a press the button

     class ListaProdutosAdapter(
         private val context: Context,
         produtos: List<Produto> = emptyList(),
         var quandoClicaNoItem: (produto: Produto) -> Unit = {}
      ) : RecyclerView.Adapter<ListaProdutosAdapter.ViewHolder>() {



    override fun onOptionsItemSelected(item: MenuItem): Boolean {

    private val adapter = ListaProdutosAdapter(context = this) 
    val db = AppDatabase.instancia(this)
    val produtoDao = db.produtoDao()

    //menu_ordem_asc_id being the button id
    when (item.itemId) {
        R.id.menu_ordem_asc_id -> {
            produto?.let { produtoDao.getAllSortedByName()}
            adapter.atualiza(produtoDao.buscaTodos())

            //This is in another class, but i put it here so it's easier to understand
            fun atualiza(produtos: List<Produto>) {
                this.produtos.clear()
                this.produtos.addAll(produtos)
                notifyDataSetChanged()
            } 
            
        }
    return super.onOptionsItemSelected(item)
}

Solution

  • Well, produtoDao.getAllSortedByName() doesn't sort the items in place, it returns a list of sorted items. So when you do produto?.let { produtoDao.getAllSortedByName()} you don't do anything with the result which is the sorted list.

    On the next line you call adapter.atualiza(produtoDao.buscaTodos()) and as you mentioned in your comments produtoDao.buscaTodos() returns an unsorted list of products. And this is what you populate your adapter with.

    In order to populate the adapter with the sorted list you should call adapter.atualiza(produtoDao.getAllSortedByName()) instead.