Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Android – filter data from database in an adapter

I am learning Kotlin and am trying to filter some data coming straight from a (room) database into my adapter to display them.

Here’s my code (from within the fragment, containing a recycleview with adapter):

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = LatestReleaseListAdapter {
        }
        binding.recyclerView.layoutManager = LinearLayoutManager(this.context)
        binding.recyclerView.adapter = adapter

        viewModel.allItems.observe(this.viewLifecycleOwner) { items ->
            //Here I'd like to remove the items that has been seen already
            items.filter { item -> !item.hasBeenSeen }
            items.let {
                adapter.submitList(it)
            }
        }  

The code is quite straight forward as you can see. I am simply trying to filter the element of the list where the boolean "hasBeenSeen"is true. I only want to show the ones where the boolean "hasBeenSeen"is false. How can I achieve that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The call to filter will filter the items and return a new collection that will contain just the filtered items.
So you could do something like this

val filteredItems = items.filter { item -> !item.hasBeenSeen }
adapter.submitList(filteredItems)

Or keep it short

adapter.submitList(items.filter { item -> !item.hasBeenSeen })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading