DEV Community

loizenai
loizenai

Posted on

Kotlin SQLite example - Search with Listview | Android

https://grokonez.com/android/kotlin-sqlite-example-search-with-listview-android

In previous post, we had known how to make CRUD operations with Android ListView. In this tutorial, we're gonna look at how to implement Search function with SearchView.

Related posts:

I. Technologies

  • Android Studio 3
  • Kotlin 1.1.51

    II. Overview

    1. Goal

    We have had an Android App that supports showing, inserting, editing, deleting Notes from/to SQLite Database with ListView:

kotlin-sqlite-goal

In this tutorial, we will add Search function for this app:

kotlin-sqlite-search-goal

2. Search function

2.1 SearchView

SearchView widget is available from Android 3.0. It is recommended to insert the search widget as an action view in the app bar.

For example, enable the widget during the onCreateOptionsMenu() callback:


override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.menu_main, menu)

    val searchView: SearchView = menu!!.findItem(R.id.searchNote).actionView as SearchView
    val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager

    searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
    searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {

        override fun onQueryTextSubmit(query: String): Boolean {
            loadQuery("%" + query + "%")
            return false
        }

        override fun onQueryTextChange(newText: String): Boolean {
            return false
        }
    })

We need to enable assisted search for each SearchView by calling setSearchableInfo() and passing it the SearchableInfo object that represents searchable configuration.

More at:

Kotlin SQLite example - Search with Listview | Android

https://grokonez.com/android/kotlin-sqlite-example-search-with-listview-android

Top comments (0)