你需要在代码中添加以下代码,然后重新启动Android Studio,就可以在运行时检查数据库了。
androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.room.Room
import androidx.room.RoomDatabase
...
//创建数据库实例
val db = Room.databaseBuilder(
applicationContext,
MyDatabase::class.java, "database-name"
).build()
//在这里添加代码以启用数据库检查器
if (BuildConfig.DEBUG) {
val db = Room.databaseBuilder(
applicationContext,
MyDatabase::class.java, "database-name"
)
.allowMainThreadQueries()
.build()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val builder = AndroidSqliteDriver.Companion.inMemoryDatabaseBuilder(
InstrumentationRegistry.getInstrumentation().context,
MyDatabase.Schema
)
val driver = builder.build()
val database = MyDatabase(driver)
} else {
val driver = AndroidSqliteDriver(dbHelper)
val database = MyDatabase(driver)
}
Stetho.initializeWithDefaults(this)
val initializerBuilder = Stetho.newInitializerBuilder(this)
initializerBuilder.enableWebKitInspector(
Stetho.defaultInspectorModulesProvider(this)
)
initializerBuilder.enableDumpapp(
Stetho.defaultDumperPluginsProvider(this)
)
initializerBuilder.enableWebKitInspector(
Stetho.defaultInspectorModulesProvider(this)
)
initializerBuilder.build()
}
//定义数据库实体
@Entity
data class User(
@PrimaryKey val uid: Int,
@ColumnInfo(name = "first_name") val firstName: String?,
@ColumnInfo(name = "last_name") val lastName: String?
)
//定义数据库访问对象
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAll(): List
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
fun loadAllByIds(userIds: IntArray): List
@Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
fun findByName(first: String, last: String): User
@Insert
fun insertAll(vararg users: User)
}
//定义数据库
@Database(entities = [User::class], version = 1)
abstract class MyDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
@Volatile
private var INSTANCE: MyDatabase? = null
fun getDatabase(context: Context): MyDatabase {
val tempInstance = INSTANCE
if (tempInstance != null)