Loading data into an android database

AutoCompleteTextView
I wanted to demonstrate how it is possible to back an AutoCompleteTextView with data from a database Cursor. To do this I needed to put a few thousand rows of data into the SQLite database on the device.

I got my list of words here:
http://www.wordlistgenerator.net/

I just left it with the default options to give me a nice long list. I took the apostrophes out to avoid having to escape them - I am only looking for semi junk input afterall.

Location of 'words' file
I saved the list into a file called 'words'. Note that there is no extension here. I am going to use this as a resource in Android and the extension interferes with this. I dropped the file into my res/drawable folder (as good as any) in order to be able to access it with my load method below.





Then I used the following code to load the rows from words into the database:

public void load() {
SQLiteDatabase db = getReadableDatabase();
try {
InputStream is = context.getResources().openRawResource(
R.drawable.words);
InputStreamReader fr = new InputStreamReader(is);
LineNumberReader fis = new LineNumberReader(fr);
String line = null;
do {
line = fis.readLine();
if (line != null) {
// do the insert
Log.d("value", line);
db.execSQL("insert into vals (val) values('" + line + "')");
}
} while (fis.readLine() != null);


} catch (Exception e) {
e.printStackTrace();
}
db.close();
}

It is important to do this work either on a background thread (using AsyncTask would be fine), or for once off or demo purposes you can just run it from a button click. If on the other hand you put this in the init code for an Activity - onCreate or onResume for example the Activity launch will time out waiting for this long execution to return. Your database will only contain a subset of the full word list which is not what you were after.









Comments

Popular posts from this blog

AutoCompleteTextView backed with data from SQLite in Android

Exporting drawings from Inkscape using the command line

Using Google Analytics in Android