您好,我正在开发新闻应用程序,我已经使用kotlin协程实现了会议室数据库,我想要实现的目标是,我想先获取数据,然后重新放置我要保存到会议室数据库中的数据,但是在数据库实现下根本不显示数据/ p>
@Database(entities = [Article::class], version = 1, exportSchema = false)
@TypeConverters(SourceTypeConverters::class)
abstract class SportNewsDatabase : RoomDatabase() {
abstract fun sportNewsDao(): SportNewsDao
companion object {
private var instance: SportNewsDatabase? = null
fun getInstance( context: Context): SportNewsDatabase? {
if (instance == null) {
synchronized(SportNewsDatabase::class.java) {
instance = Room.databaseBuilder(context.applicationContext, SportNewsDatabase::class.java, "article_database")
.fallbackToDestructiveMigration()
.build()
}
}
return instance
}
}
}
SportNewsDao.kt
@Dao
interface SportNewsDao {
@Query("SELECT * FROM Article")
fun getAllData(): LiveData<List<Article>>
@Insert
suspend fun addAll(article: List<Article>)
@Update
suspend fun updateArticle(article: Article)
@Delete
suspend fun deleteArticle(article: Article)
}
NewsRepository.kt以下
class NewsRepository(private val sportNewsApi: SportNewsInterface, private val sportNewsDao: SportNewsDao) {
val data = sportNewsDao.getAllData()
suspend fun refresh() {
withContext(Dispatchers.IO) {
val articles = sportNewsApi.getNewsAsync().body()?.articles
if (articles != null) {
sportNewsDao.addAll(articles)
}
}
}
}
MainViewModel.kt下面
@Suppress("UNCHECKED_CAST")
class MainViewModel(val newsRepository: NewsRepository) : ViewModel(), CoroutineScope {
// Coroutine's background job
val job = Job()
// Define default thread for Coroutine as Main and add job
override val coroutineContext: CoroutineContext = Dispatchers.Main + job
val showLoading = MutableLiveData<Boolean>()
val sportList = MutableLiveData<List<Article>>()
val showError = SingleLiveEvent<String>()
fun loadNews() {
// Show progressBar during the operation on the MAIN (default) thread
showLoading.value = true
// launch the Coroutine
launch {
// Switching from MAIN to IO thread for API operation
// Update our data list with the new one from API
val result = withContext(Dispatchers.IO) {
newsRepository?.data
newsRepository.refresh()
}
}
}
}
我想知道我在哪里出错了,为了正确保存对数据库的响应并将数据显示给我的android应用程序,我必须做什么。
答案 0 :(得分:0)
这可以帮助您调试正在发生的事情。 您可以使用设备文件资源管理器在手机上获取创建的数据库文件
查看->工具窗口->设备文件资源管理器。
然后导航到数据库所在的位置,并将其下载到您的PC上。
下载SQLite数据库浏览器并检查数据库。