【问题标题】:Room automatically sorts on the basis of primary key in Android房间根据Android中的主键自动排序
【发布时间】:2019-03-14 05:09:45
【问题描述】:

我有一个这样的数据类

@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 中我有这样的保存和获取方法

    @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 对列表进行排序。

所以如果我用id:254id:23id:45id:92 保存问题,那么我会得到这样的id:23id:45id:92id:254

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

【问题讨论】:

  • 除了添加另一列作为日期之外,您是否找到任何解决方案?

标签: android sqlite kotlin android-room


【解决方案1】:

尝试使用 autoGenerate = true 作为主键,这样它会按顺序创建 PK 号

看下面几行

@PrimaryKey(autoGenerate = true)

所以现在您的插入和检索顺序将相同

【讨论】:

    【解决方案2】:

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

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

    并按日期对您的实体进行排序

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

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多