【发布时间】:2019-05-14 14:12:47
【问题描述】:
在我的 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)
}
}
}
国家代码实体
@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 接口
@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(这意味着没有结果)。但是在下一次查询和下一次启动期间,它工作得非常好——它根据 order 参数返回 7 和 34。 所以我对那个错误感到非常困惑。请帮我解决这个问题
【问题讨论】:
-
我的事情是因为您正在异步填充数据尝试在
Executors.newSingleThreadScheduledExecutor().execute { //here }内部执行回调
标签: android android-sqlite android-room android-architecture-components