Android AutoCompleteTextView with a sqlite database

In too many of my Android projects, I’ve needed to implement an AutoCompleteTextView that was backed by a sqlite database. It was always way more work than it should have been. After my last project, I decided to pare down the code and form it into a library for future use. After doing that, I decided to start make it available publicly via my first public GitHub repository. Then, to complete the geeky Internet cycle of life, I’ve decided to write a blog post about it. And here we are.

If you’d like to go straight to the code, be my guest:

GitHub Repository for my Android DatabaseAutoCompleteLibrary

The central idea was to make it dead simple to connect a locally-stored sqlite database with an AutoCompleteTextView for custom autocomplete awesomeness. I think I did it, but I’ll wait for glory to be heaped upon my by the anonymous Internet before getting too excited.

The only class that you would need to explicitly instantiate is AutoCompleteListener (in my com.littlepancake.android.utils package). All of the magic happens in there. All you need to set in that class is the Context, AutoCompleteTextView that will be fed by the results, a locally-stored sqlite database, the table you want to query within that database, and the column that you’d like returned from within that table. All-in-all it looks something like this (from within your main Activity’s onCreate, for example):


...
/* Have a name for your db (already stored on the device). */
String dbName = "my.db";

/* Make sure the path leading to that db is correct. */
dbDir = this.getDatabasePath(dbName).getAbsolutePath();

/* Grab handle to your AutoCompleteTextView. */
mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete_example);

/* Create a new listener, pass in context, AutoCompleteTextView, and a database name. */
mAutoCompleteListener = new AutoCompleteListener(this, mAutoCompleteTextView, dbName);

/* Make some customizations as necessary. */
mAutoCompleteListener.setDbName(dbName);
mAutoCompleteListener.setLimit(20);
mAutoCompleteListener.setColName("country");
mAutoCompleteListener.setTableName("countries");

...

And that’s all she wrote. At that point, the AutoCompleteTextView will populate with data from the “my.db”. Specifically, from the table named “countries” the autocomplete will show entries from the “country” column.

Obviously there are a lot of ways this could be improved, but this setup is sufficient for many of my AutoCompleteTextView needs. Therefore I thought it would be helpful for others. I’ve received so much guidance from Internet searches and sites like stackoverflow, github, and others that I thought I might throw a little code back into the pool to see if anyone else might benefit.

Littlepancake Software by Littlepancake Software