0

I'm calling a method to see if there is a value inside the database.

    String[] columns ={table.NAME};
    String[] selectionsArgs = {name};
    Cursor cursor = db.query(table.TABLE_NAME, columns, table.NAME+"= ?", selectionsArgs,null, null, null, null);

    int index = cursor.getColumnIndex(table.ID);

Irrespective of whether the name exists or not the index is always -1. Why ?

Varun Nath
  • 5,570
  • 3
  • 23
  • 39
user3716096
  • 11
  • 1
  • 3

2 Answers2

1

Irrespective of whether the name exists or not the index is always -1. Why ?

Because you didn't include table.ID in columns.

getColumnIndex() can only find columns that are there in the cursor, irrespective of whether there are any rows.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • If i add table.ID i always get 0, no matter what – user3716096 Aug 01 '14 at 05:25
  • 1
    Because it's the *index* of the id column. If you want a value, use one of the `moveTo...()` to move to a valid row (check the return value) and e.g. `getInt(index)` to get the value as int. – laalto Aug 01 '14 at 05:29
  • Ty laalto u were right and my query was fine the problem was how i was using getColumnIndex() – user3716096 Aug 01 '14 at 14:12
-1

Even without the table at hand, seems a lot like you are creating the query wrong.

Strange things I see:

  1. Using table.NAME for the columns name.
  2. Using table.NAME also for the WHERE clause condition
  3. Having an extra space in that "= ?"

Try with:

Cursor cursor = db.query(table.TABLE_NAME ,null ,null ,null ,null, null, null, null);

Also, check this answer out for reference: SQLiteDatabase.query method

Community
  • 1
  • 1
Mikel Pascual
  • 2,202
  • 18
  • 27
  • Name of his table is `table.TABLE_NAME` not `table.NAME`, so what should be strange with this? – frogatto Aug 01 '14 at 04:33
  • Did the query I proposed work? If it works, that means that the query on your question was wrong (so you would have to provide the table structure or check the reference). If it doesn't work, the table is empty. – Mikel Pascual Aug 01 '14 at 04:36