Search code examples
androidcursorandroid-sqlite

Cursor does not get values from database


Im trying to get some values from my database using Cursor. My problem is that when i try to get the values out of my DB my Cursor out of bounds. Im sure that the values that i want exists in the DB because i have other method that can get those values. I want to get the value from COLUMN_FIELDS_PARAMETER

log cat:

05-09 11:24:17.872: E/AndroidRuntime(4113): FATAL EXCEPTION: main
05-09 11:24:17.872: E/AndroidRuntime(4113): android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
05-09 11:24:17.872: E/AndroidRuntime(4113):     at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)

here is my code: putting the values:

public void putParameters(int[] parameters, String exercise) {

    String parametersList = "";

    for(int i = 0; i < parameters.length; i++){

        if (parameters[i] != 0)
        {
            parametersList = parametersList + " " + parameters[i];
        }
    }   

    ContentValues cv = new ContentValues();
    cv.put(COLUMN_FIELDS_PARAMETER, parametersList);
    cv.put(COLUMN_EXERCISE, exercise);

    String whereClause = COLUMN_FIELDS_PARAMETER + "= ? and " + COLUMN_EXERCISE + "= '" +  exercise + "'";
    String[] columns = new String[]{COLUMN_EXERCISE, COLUMN_FIELDS_PARAMETER};

    Cursor c = ourDatabase.query(TABLE_NAME, columns, whereClause , null, null, null, null, null);

    if(c == null)
        ourDatabase.insert(TABLE_NAME, null, cv);
    else
        ourDatabase.update(TABLE_NAME, cv, whereClause, null);
}



  public String getParameters(String exercise){

    String foo = "";

    String whereClause = COLUMN_FIELDS_PARAMETER + "= ? and " + COLUMN_EXERCISE + "= '" +  exercise + "'";
    String[] columns = new String[]{COLUMN_EXERCISE, COLUMN_FIELDS_PARAMETER};

    Cursor c = ourDatabase.query(TABLE_NAME, columns, whereClause , null, null, null, null);

    int parameter = c.getColumnIndex(COLUMN_FIELDS_PARAMETER);

        if (c != null)
        {
            c.moveToFirst();
            foo = c.getString(parameter);
            return foo;
        }   

    return foo;
}

Solution

  • You're missing the whereParameters that goes with the whereClause. Try this:

    String whereClause = COLUMN_FIELDS_PARAMETER + "= ? and " + COLUMN_EXERCISE + "= '?'";
    String[] whereParams = {field, exercise};
    
    Cursor c = ourDatabase.query(TABLE_NAME, columns, whereClause , whereParams, null, null, null);
    

    Note that the whereClause has two ?. For each one you need to provide a value, in the String[] whereParams and pass it to the query. What it does is substitue each ? with the correct value (in the example above with field and exercise. This protects you from SQL injection (so user cannot enter SQL commands in exercise.