Loading data into an android database
AutoCompleteTextView |
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 |
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
Post a Comment