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:
Kotlin ListView example | Android
Kotlin SQLite example – CRUD operations with ListView | Android

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:

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

Then we get a reference to the SearchableInfo by calling getSearchableInfo() on SearchManager.

We also need to set callbacks for changes to the query text by using setOnQueryTextListener(). In onQueryTextSubmit() function, we call loadQuery() function with parameter as input string from the search bar.

2.2 Query

A query can be created via:
rawQuery() or query()
SQLiteQueryBuilder

For example:

When having Cursor object, we can traverse all records from Query:

3. Project Structure

kotlin-sqlite-search-structure

This project bases on source code from SQLite CRUD operations with ListView. We add:
– new item to Menu (menu_main.xml)
– MainActivity:
+ replace loadQueryAll() with loadQuery(string) function
+ add SearchView widget to menu (onCreateOptionsMenu() function)
– NoteDbManager: add query fucntion

III. Practice

1. Set up Project

– Import project from previous post: CRUD operations with ListView.
– Add images (found in source code) to drawable.

2. Database Manager

Open NoteDbManager.kt, add query() function:

3. Add SearchView widget
3.1 Main Menu

3.2 Main Activity

– Add function for query:

– Add code for SearchView widget:

– Change all loadQueryAll() statements to loadQuery("%") statements.

IV. Source Code

Kotlin-SQLite-Search-ListView

By grokonez | December 10, 2017.

Last updated on July 13, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*