Search code examples
androidkotlinfiltersearchview

Why is my adapter unresolved when I'm trying to access its filter


I have an activity which has a RecyclerView I'd like to filter using a SearchView I set up.

class ExerciseCatalogueActivity : AppCompatActivity(), ExerciseClickedListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_exercise_catalogue_activity)
        val toolbar = toolbar_catalogue
        setSupportActionBar(toolbar)

        val exercisesCatalogueList : MutableList<Exercise>
        val exerciseCatalogueFullList: MutableList<Exercise>

        val exerciseFileString: String = resources.openRawResource(R.raw.exercises1).bufferedReader().use { it.readText() }

        exercisesCatalogueList = (Gson().fromJson(exerciseFileString, Array<Exercise>::class.java)).toMutableList()
        exerciseCatalogueFullList = ArrayList<Exercise>(exercisesCatalogueList)

        rv_catalogue.apply {
            rv_catalogue.layoutManager = LinearLayoutManager(context, LinearLayout.VERTICAL, false)
            adapter = ExerciseCatalogueRecyclerViewAdapter(exercisesCatalogueList,exerciseCatalogueFullList, this@ExerciseCatalogueActivity)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.toolbar_menu, menu)
        val searchItem = menu!!.findItem(R.id.action_search_bar)
        val searchView = searchItem.actionView as SearchView

        searchView.imeOptions = EditorInfo.IME_ACTION_DONE

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String): Boolean {
                adapter.filter.filter(newText)
                return false
            }
        })
        return true
    }
}

However adapter.filter.filter(newText) returns as unresolved and I cannot filter my recyclerView. What changes need to be made?


Solution

  • You haven't saved a reference to your adapter.

    You use .apply on the RecyclerView called rv_catalogue, so that works inside the scope.

    In onCreateOptionsMenu, there is no adapter to reference.

    Either save a reference to the adapter in your Activity, or use rv_catalogue.adapter to get a reference to the adapter.