簡體   English   中英

插入前的 Android Room 解析

[英]Android Room parse before inserting

想象一下從端點接收這樣的對象

data class Foo(
    val name: String,
    val start: String,
    val end: String
)

其中屬性startend是格式為“00:00:00”的字符串,表示從午夜開始的小時、分鍾和秒。

我需要將此對象保存在 Room 表中,但將開始和結束解析為 Int 而不是字符串。

我采用的解決方案是這樣的:

data class Foo(
    val name: String,
    val start: String,
    val end: String,
    var startInSeconds: Int = 0,
    var endInSeconds: Int = 0
) {
    init {
        startInSeconds = this.convertTimeInSeconds(this.start)
        endInSeconds = this.convertTimeInSeconds(this.end)
    }

    private fun convertTimeInSeconds(time: String): Int {
        val tokens = time.split(":".toRegex())
        val hours = Integer.parseInt(tokens[0])
        val minutes = Integer.parseInt(tokens[1])
        val seconds = Integer.parseInt(tokens[2])
        return 3600 * hours + 60 * minutes + seconds
    }
}

但我想避免每次都解析開始和結束。

有沒有辦法在插入前解析?

如果你願意,你可以試試我的解決方案,

  1. 首先,與其使用同一個對象Foo來存儲您的數據,不如創建另一個data class作為Entity封裝數據。
data class Bar(
    val name: String,
    val start: String,
    val end: String,
    val startInSeconds: Int, // <<-- using val to make data read only
    val endInSeconds: Int // <<-- using val to make data read only
) 
  1. 您可能需要創建一千個object ,具體取決於您的數據大小,因此使用companion object似乎是解析數據以避免不必要的內存分配的好主意。
data class Bar(
    val name: String,
    val start: String,
    val end: String,
    val startInSeconds: Int,
    val endInSeconds: Int
) {

  companion object {
        // overloading the invoke function
        operator fun invoke(foo:Foo) : Bar {
            return Bar(
               name = foo.name,
               start = foo.start,
               end = foo.end,
               startInSeconds = convertTimeInSeconds(foo.start),
               endInSeconds = convertTimeInSeconds(foo.end)
            )
        }

        private fun convertTimeInSeconds(time: String): Int {
           val tokens = time.split(":".toRegex())
           val hours = Integer.parseInt(tokens[0])
           val minutes = Integer.parseInt(tokens[1])
           val seconds = Integer.parseInt(tokens[2])
           return 3600 * hours + 60 * minutes + seconds
       }
    } 

}
//how to use
fun insertToDatabase(foo:Foo){
   val parsedData = Bar(foo)
   dao.insert(parsedData)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM