我正在开发新闻Android,我已经实现了要实现的空间数据库逻辑,我想先获取数据,然后保存到空间数据库,但是当我运行该应用程序时,我已经实现了该逻辑,它只显示白屏进度栏加载
下面是Android应用的屏幕截图
在MainViewmModel.kt类下面
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()
}
}
}
}
在我的NewsRepository下,我正在其中获取数据并将其保存到数据库
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)
}
}
}
}
NewsDao.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)
}
SportNewsDatabase.kt以下
@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
}
}
}
我想知道我在哪里出错,为什么应用程序显示空白屏幕