我正在开发新闻应用程序,但TopHeadlinesFragment加载进度栏未显示来自服务器的响应我想知道我在哪里弄错了我必须做些什么才能显示来自服务器的响应
在我的应用程序屏幕截图下方
在我的TopHeadlinesFragment.kt下面
class TopHeadlinesFragment : Fragment() {
private lateinit var binding: FragmentTopHeadlinesBinding
private val viewModel by viewModel<MainViewModel>()
private lateinit var topHeadlinesAdapter: TopHeadlinesAdapter
// private val newsRepository: NewsRepository by inject()
//3
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =
DataBindingUtil.inflate(inflater, R.layout.fragment_top_headlines, container, false)
binding.lifecycleOwner = this
topHeadlinesAdapter = TopHeadlinesAdapter()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViewModel()
// loadingAds()
}
private fun initViewModel() {
viewModel.sportList.observe(this, Observer { result ->
when (result) {
is Results.Success -> {
val newList = result.data
if (newList != null) {
topHeadlinesAdapter.updateData(newList)
}
binding.recyclerView.adapter = topHeadlinesAdapter
topHeadlinesAdapter.notifyDataSetChanged()
viewModel.showLoading.observe(this, Observer {showLoading ->
pb.visibility = if (showLoading) View.VISIBLE else View.GONE
})
}
is Results.Failure -> {
viewModel.showLoading.observe(this, Observer {showLoading ->
pb.visibility = if (showLoading) View.INVISIBLE else View.GONE
})
}
}
viewModel.loadNews()
})
}
}
低于NewsRepository.kt
class NewsRepository(
private val sportNewsApi: SportNewsInterface,
private val sportNewsDao: SportNewsDao
) {
companion object{
const val TAG= "Error"
}
val data = sportNewsDao.getAllData()
suspend fun refresh() = withContext(Dispatchers.IO) {
val articles = sportNewsApi.getNewsAsync().body()?.articles
if (articles != null) {
sportNewsDao.addAll(articles)
Log.e(TAG,"Error")
Results.Success(articles)
} else {
Results.Failure("MyError")
}
}
}
在我的MainViewModel.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
private val _showLoading = MutableLiveData<Boolean>()
private val _sportList = MutableLiveData<Results>()
val showLoading: LiveData<Boolean>
get() = _showLoading
val sportList: LiveData<Results>
get() = _sportList
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 = newsRepository.refresh()
_sportList.value = result
_showLoading.value = false
}
}
override fun onCleared() {
job.cancel()
}
}