【发布时间】:2020-07-21 08:36:18
【问题描述】:
大家好,我正在开发新闻应用程序我已经用 kotlin 协程实现了房间数据库我想要实现的目标我想先获取数据然后响应我想保存到房间数据库但数据根本没有显示在我的数据库实现下面
@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 应用程序。
【问题讨论】:
标签: android kotlin mvvm android-room kotlin-coroutines