1

I have a database of 23,000 words. I want to have the query return all words that start with a certain search string. After reading sqlite LIKE problem in android I was able to get a working query using LIKE. Here it is:

SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

String [] sqlSelect = { KEY_WORD };
String sqlTables = TABLE_WORDS;
//String selection = KEY_FUZZYWORD + " =?"; // for an exact match
String selection = KEY_FUZZYWORD + " LIKE ?";
String[] selectionArgs = { searchString + "%" };
String limit = Integer.toString(WORD_QUERY_LIMIT);

qb.setTables(sqlTables);
Cursor cursor = qb.query(db, sqlSelect, selection, selectionArgs, null, null, null, limit);

The key lines are

String selection = KEY_FUZZYWORD + " LIKE ?";
String[] selectionArgs = { searchString + "%" };

But I also read Why do we need the GLOB clause in SQLite? Case sensitivity is fine for my situation so I thought I would try it. How do you set this up using SQLiteQueryBuilder with selectionArgs? I was having a lot of trouble finding an example. (I don't want to use a rawQuery in order to avoid SQL injection.)

Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

1 Answers1

2

It is very similar to what you have already.

SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

String [] sqlSelect = { KEY_WORD };
String sqlTables = TABLE_WORDS;
String selection = KEY_FUZZYWORD + " GLOB ?";
String[] selectionArgs = { searchString + "*" };
String limit = Integer.toString(WORD_QUERY_LIMIT);

qb.setTables(sqlTables);
Cursor cursor = qb.query(db, sqlSelect, selection, selectionArgs, null, null, null, limit);

the key lines being

String selection = KEY_FUZZYWORD + " GLOB ?";
String[] selectionArgs = { searchString + "*" };

Further reading:

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393