Search code examples
androidsqlitesqlexception

SQLiteException when querying in Android


I receive this exception "bind or column index out of range" in this line:

Cursor cursor = db.query(TABLE_NAME, null, ID, new String[] { id }, null, null, null);

I want to check if the given id exists in the database, but always the query throw this exception and I don't know what is wrong. I tried with this and the exception it's the same:

Cursor cursor = db.query(TABLE_NAME, null, ID+" = ?", new String[] { id }, null, null, null);

This is the method I've programmed. If there is something wrong here, please, tell me:

public boolean existsAcc(String id)
    {
        //Check the parameters
        if (id == null)
        {
            throw new IllegalArgumentException(
                    "The id parameter cannot be null");
        }
        SQLiteDatabase db = getReadableDatabase();

        Cursor cursor = db.query(TABLE_NAME, null, ID, new String[] { id }, null, null, null);

        if (!cursor.moveToFirst())
        {
            cursor.close();
            return false;
        }

        cursor.close();

        return true;
    }

Solution

  • I don't know why Chirag deleted his answer, but he was rigth. Changing

    Cursor cursor = db.query(TABLE_NAME, null, ID, new String[] { id }, null, null, null);
    

    to

    Cursor cursor = db.query(TABLE_NAME, null, ID + " = '" + id + "'", null, null, null, null);
    

    does the trick.