Home » Android » java – Android: SQL rawQuery with wildcard (%)

java – Android: SQL rawQuery with wildcard (%)

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m having a rawQuery() with following sql string similar to this:

selectionArgs = new String[] { searchString };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);

but now I have to include a wildcard in my search, so my query looks something like this:

SELECT column FROM table WHERE column LIKE ‘searchstring%’

But when the query contains single quotes the following SQLite Exception is thrown: android.database.sqlite.SQLiteException: bind or column index out of range

How can I run a rawQuery with selectionArgs inside a SQL query with wildcard elements?

How to&Answers:

You have to append the % to the selectionArgs itself:

selectionArgs = new String[] { searchString + "%" };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);

Note: Accordingly % and _ in the searchString string still work as wildcards!

Answer:

The Sqlite framework automatically puts single-quotes around the ? character internally.

String [] selectionArgs = {searchString + "%"};
Cursor c;
// Wrap the next line in try-catch
c = db.rawQuery("SELECT column FROM table WHERE like ?", selectionArgs);

That’s it.

Answer:

Brad Hein’s and Mannaz’s solution did not work for me, but this did:

String query = "SELECT column FROM table WHERE column=%s";
String q = String.format(query, "\""+searchString + "%\"");
Cursor c = db.rawQuery(q, null);