Storing and Searching for Data

There are many ways to store your data, such as in an online database, in a local SQLite
database, or even in a text file. It is up to you to decide what is the best solution for your
application. This lesson shows you how to create a SQLite virtual table that can provide robust
full-text searching. The table is populated with data from a text file that contains a word and
definition pair on each line in the file.

Create the Virtual Table

A virtual table behaves similarly to a SQLite table, but reads and writes to an object in
memory via callbacks, instead of to a database file. To create a virtual table, create a class
for the table:

Java

Create an inner class in DatabaseTable that extends SQLiteOpenHelper. The SQLiteOpenHelper class
defines abstract methods that you must override so that your database table can be created and
upgraded when necessary. For example, here is some code that declares a database table that will
contain words for a dictionary app:

Populate the Virtual Table

The table now needs data to store. The following code shows you how to read a text file
(located in res/raw/definitions.txt) that contains words and their definitions, how
to parse that file, and how to insert each line of that file as a row in the virtual table. This
is all done in another thread to prevent the UI from locking. Add the following code to your
DatabaseOpenHelper inner class.

Tip: You also might want to set up a callback to notify your UI
activity of this thread's completion.

Java

Search for the Query

When you have the virtual table created and populated, use the query supplied by your SearchView to search the data. Add the following methods to the
DatabaseTable class to build a SQL statement that searches for the query:

Search for a query by calling getWordMatches(). Any matching results are returned
in a Cursor that you can iterate through or use to build a ListView.
This example calls getWordMatches() in the handleIntent() method of the searchable
activity. Remember that the searchable activity receives the query inside of the ACTION_SEARCH intent as an extra, because of the intent filter that you
previously created: