Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQLiteException: bind or column index out of range problem

Tags:

android

sqlite

In android I am using the following statement.

model = dataHelper.rawQuery("SELECT _id, engword, lower(engword) as letter FROM word WHERE letter >= 'a' AND letter < '{' AND engword LIKE '%" + filterText + "%'", new String[ {"_id","engword", "lower(engword) as letter"});

It is throwing android.database.sqlite.SQLiteException: bind or column index out of range: handle 0x132330

What is the problem in my code?

like image 352
dev_android Avatar asked Apr 19 '11 12:04

dev_android


3 Answers

You provided 3 parameters but you have no ? in your query. Pass null instead of string array as the 2nd argument to the rawQuery or replace _id, engword and lower(engword) as letter in your select string by ?

1)

model = dataHelper.rawQuery("SELECT ?, ?, ? FROM word WHERE letter >= 'a' AND letter < '{' AND engword LIKE '%" + filterText + "%'",new String[] {"_id","engword", "lower(engword) as letter"});

2)

model = dataHelper.rawQuery("SELECT _id, engword, lower(engword) as letter FROM word WHERE letter >= 'a' AND letter < '{' AND engword LIKE '%" + filterText + "%'", null);

Edit: As @Ewoks pointed out, the option (1) is incorrect, since prepared statements can get parameters (?s) only in WHERE clause.

like image 36
ernazm Avatar answered Nov 18 '22 16:11

ernazm


The right statement is :

model = dataHelper.rawQuery("
    SELECT _id, engword, lower(engword) as letter
    FROM word W
    HERE letter >= 'a'
    AND letter < '{'
    AND engword LIKE ? ORDER BY engword ASC
    ",
    new String[] {"%" + filterText + "%"}
);
like image 188
dev_android Avatar answered Nov 18 '22 15:11

dev_android


If anyone is like me trying (and failing) to get this working with getContentResolver().query here how I managed it:

*Updated thanks to comments from @CL and @Wolfram Rittmeyer, as they said this is the same as for rawQuery *

Correct way:

  public static String SELECTION_LIKE_EMP_NAME = Columns.EMPLOYEE_NAME
            + " like ?";            

  Cursor c = context.getContentResolver().query(contentUri,
                PROJECTION, SELECTION_LIKE_EMP_NAME, new String[] { "%" + query + "%" }, null);

Previous answer that was open to SQL injection attack:

public static String SELECTION_LIKE_EMP_NAME = Columns.EMPLOYEE_NAME
            + " like '%?%'";

String selection = SELECTION_LIKE_EMP_NAME.replace("?", query);

Cursor c = context.getContentResolver().query(contentUri,
            PROJECTION, selection, null, null);
like image 41
scottyab Avatar answered Nov 18 '22 16:11

scottyab