Room在Android中根据主键自动排序 [英] Room automatically sorts on the basis of primary key in Android

查看:1069
本文介绍了Room在Android中根据主键自动排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据类

I have a data class like this

@Entity
data class Question(

        @field:SerializedName("question")
        var question: String? = null,

        @field:SerializedName("answers")
        var answers: ArrayList<String?>? = null,

        @field:SerializedName("id")
        @PrimaryKey
        var id: Int? = null
)

然后在DAO中,我保存并获取了这样的方法

Then in DAO I have saving and getting methods like this

    @Dao
interface QnADao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun saveQuestion(questions:Question)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun saveAllQuestions(questions: List<Question?>?)


    @Query("SELECT * from Question")
    fun getAllQnA():List<Question>


}

我要保存Questions的列表,然后稍后再检索它们.因此,每当检索它们时,我都会根据主键id对列表进行排序.

I am saving a list of Questions and then later on retrieving them. So whenever I retrieve them I get the list sorted according to the id which is the primary key.

因此,如果我保存的是id:254id:23id:45id:92的问题,那么我会像这样id:23id:45id:92id:254

So if I am saving questions with id:254, id:23, id:45 and id:92 then I am getting it like this id:23, id:45, id:92 and id:254

但是我不需要像这样的排序列表,我需要获取保存在数据库中的数据.任何帮助,将不胜感激.谢谢.

But I don't need a sorted list like that, I need to get the data as it was saved in the database. Any help would be appreciated. Thanks.

推荐答案

您可以将Date字段添加到您的Question实体

You can add a Date field to your Question entity

@field:SerializedName("date")
var date: Date? = null,

并按日期对实体进行排序

and order your entities by date

@Query("SELECT * FROM Question ORDER BY date DESC")

这篇关于Room在Android中根据主键自动排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆