Saved News Fragment

Learn how to retrieve saved news from local database.

We'll cover the following...

Saving favorite articles

This fragment will display a list of articles that the user has marked as favorites and intends to read later.

The “Favorites” button is a floating action bar that allows the user to save an article in the Room database by clicking it. The saved article(s) is then displayed in this fragment.

Let’s look at the code.

Press + to interact
class SavedNewsFragment : Fragment(R.layout.fragment_saved_news) {
lateinit var viewModel: NewsViewModel
lateinit var favouriteNewsAdapter: FavouriteNewsAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var binding = FragmentSavedNewsBinding.bind(view)
setUpRecyclerView(binding)
val newsRepository = NewsRepository(ArticleDatabase(requireContext() as NewsActivity))
val viewModelProviderFactory =
NewsViewModelProvider(activity?.application!!, newsRepository)
viewModel = ViewModelProvider(this, viewModelProviderFactory).get(NewsViewModel::class.java)
favouriteNewsAdapter.setOnItemClickListener {
val favArticle = Article(
it.id,
it.author,
it.content,
it.description,
it.publishedAt,
it.source,
it.title,
it.isBookmarked,
it.url,
it.urlToImage
)
val bundle = Bundle().apply {
putSerializable("article", favArticle)
}
findNavController().navigate(
R.id.action_savedNewsFragment2_to_articleFragment,
bundle
)
}
lifecycleScope.launch {
viewModel.fetchSavedArticles().collect {
favouriteNewsAdapter.favouriteNewsDifferCallBack.submitList(it)
}
}
}
private fun setUpRecyclerView(binding: FragmentSavedNewsBinding) {
favouriteNewsAdapter = FavouriteNewsAdapter()
binding.SavedNewsRecyclerView.apply {
adapter = favouriteNewsAdapter
layoutManager = LinearLayoutManager(activity)
}
}
}

We start by declaring three class variables:

lateinit var viewModel: NewsViewModel
lateinit var favouriteNewsAdapter: FavouriteNewsAdapter

These are class variables that will be assigned values later in the program, and because we used the lateinit modifier, we’ll delay their initialization until later on in the program. However, it should be ...