30

Hello i've spent almost 2 hours trying to figure out why the LIKE statement doesn't work and i only get this error: 03-03 11:31:01.770: ERROR/AndroidRuntime(11767): Caused by: android.database.sqlite.SQLiteException: bind or column index out of range: handle 0x89d9f8

In SQLiteManager it works perfectly like this: SELECT Word FROM Sign WHERE Word LIKE 'he%'; But when i try to do it from java it won't work. Here's is my query, i've tried in a lot of ways with no luck:

Cursor cursor = m_db.query(MY_TABLE, new String[] {"rowid","Word"},"Word"+" LIKE '"+" ?"+"%'", new String[]{name}, null, null, null);

Any ideas? i'm i doing it wrong or is there a bug?

Thanks for your time.

madcoderz
  • 4,423
  • 10
  • 47
  • 74

4 Answers4

61

The solution is actually very easy. Just include the % inside your selectionArgs.

String []selectionArgs = {name + "%"});
Jona
  • 13,325
  • 15
  • 86
  • 129
  • 2
    This works for me. This solution is better than the answer of Olsavage because it's not vulnerable to SQL injection. – Kowlown Sep 28 '13 at 21:53
  • @Kowlown, can you please tell me how could an sql be done in your Olsavage's method, because both seem identical to me – juztcode Aug 15 '20 at 15:47
  • @juztcode The answer has been edited with the right way to prevent SQL injection. The 2014 edit is good, and can be used. – Kowlown Aug 16 '20 at 22:28
37

I think you shouldn't use selArgs for LIKE such a way. You may try this:

Cursor cursor = m_db.query(MY_TABLE, new String[] {"rowid","Word"},"Word"+" LIKE '"+name+"%'", null, null, null, null);

EDIT:

OK, if you want be safe from SQL injections, don't use above solution, use this:

Cursor cursor = m_db.query(MY_TABLE, new String[] {"rowid","Word"},"Word LIKE '?'", new String[]{name+"%"}, null, null, null);
Olsavage
  • 1,118
  • 8
  • 11
7

This is how I did:

String []columns = {"_id", "name"};
String []selectionArgs = {name+"%"};
db.query(true,"mydb",columns,"name LIKE ?",selectionArgs,null,null,null);
Sarvar Nishonboyev
  • 12,262
  • 10
  • 69
  • 70
2

Another -- perhaps cleaner -- solution is to use the || operator as described here: Sqlite binding within string literal

Community
  • 1
  • 1
Steve Pomeroy
  • 10,071
  • 6
  • 34
  • 37