gpt4 book ai didi

android - 房间。第一个查询返回空值

转载 作者:行者123 更新时间:2023-12-01 05:51:19 28 4
gpt4 key购买 nike

在我的 Android 项目中,我使用 Room 库来处理 SQLite 数据库。我使用我的数据库来保存国家电话代码。我的数据库预装了两个国家(观看 populateDatabaseWithCountryCodes(dao: PhoneCodeDao) 函数);

@Database(entities = [CountryCode::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun createPhoneCodeDao(): PhoneCodeDao

companion object {
@Volatile
private var INSTANCE: AppDatabase? = null

fun getDatabase(context: Context): AppDatabase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"database"
).addCallback(PrepopulationCallback)
.build()
INSTANCE = instance
return instance
}
}
}

object PrepopulationCallback : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
INSTANCE?.let { database ->
GlobalScope.launch(Dispatchers.IO) {
populateDatabaseWithCountryCodes(database.createPhoneCodeDao())
}
}
}

private fun populateDatabaseWithCountryCodes(dao: PhoneCodeDao) {
val spainPhoneCode = CountryCode(0, "Spain", 34)
val rusPhoneCode = CountryCode(1, "Russia", 7)
val list = LinkedList<CountryCode>()
list.add(spainPhoneCode)
list.add(rusPhoneCode)
dao.insertAllCountryCodes(list)
}
}
}

CountryCode 实体
@Entity(tableName = "country_code")
data class CountryCode(
@SerializedName("order")
@ColumnInfo(name = "order_list") val order: Int,
@SerializedName("name")
@ColumnInfo(name = "country_name_eng") val name: String,
@SerializedName("phone_code")
@ColumnInfo(name = "phone_code") val phoneCode: Int
) {
@ColumnInfo(name = "id")
@PrimaryKey(autoGenerate = true)
var id: Long = 0
}

DAO接口(interface)
@Dao
interface PhoneCodeDao {

@Insert
fun insertAllCountryCodes(list: List<CountryCode>)

@Query("SELECT phone_code FROM country_code WHERE order_list = :order")
fun selectCountryCodeByOrder(order: Int): Int

}

在我的应用程序中,我按顺序选择国家代码(监视功能 selectCountryCodeByOrder(order: Int): Int )。我在 async{} 协程中异步调用此函数。但是我有一个很奇怪的错误: 安装后,我在设备上首次启动我的应用程序并进行查询 - 查询结果为 0(这意味着没有结果)。但是在下一次查询和下一次启动期间,它工作得很好——它相应地返回 7 和 34 到 order 参数。 所以我对那个错误很困惑。请帮我解决这个问题

最佳答案

那是因为它可能在数据库为空时查询数据库。所以解决这个问题的最好方法是返回 LiveData 而不是原始 int。然后 LiveData 将负责在填充数据库时更新 UI。

 @Query("SELECT phone_code FROM country_code WHERE order_list = :order")
fun selectCountryCodeByOrder(order: Int): LiveData<SomeType>

关于android - 房间。第一个查询返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53760541/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com