19

I am trying to get column value from a cursor, this column is generated at run time by calculations inside the query, I am getting a null value of this column, I am able to get a value of all other columns which exists in SQLite table.

I execute the same query on SQLite editor, it also shows the value of generated column in result set.

Why this giving null value when I am retrieving it from cursor?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Chandrapal Yadav
  • 277
  • 1
  • 3
  • 9

5 Answers5

61

Very Simple you can get it by either of following way

String id = cursor.getString( cursor.getColumnIndex("id") ); // id is column name in db

or

String id = cursor.getString( cursor.getColumnIndex(0)); // id is first column in db
Lucifer
  • 29,392
  • 25
  • 90
  • 143
3

Cursor column names are case sensitive, make sure you match the case specified in the db or column alias name

Rafael Nobre
  • 5,062
  • 40
  • 40
2
  1. If you don't know column index in select query the follow this,

    Define constant for all fields of table so it is easy to get field name you don't need to verify its spell

    create Database Costant class with name "DBConstant.java" and define table fields

    public static final String ID = "id";

    Then get value from cursor,

    cursor.getString(cursor.getColumnIndex(DBConstant.ID));

    cursor.getColumnIndex(field name); it returns field column index in you select statement cursor.getString(column index). it returns value which is on that column

  2. If you know column index in your select query,

    cursor.getString(0);

Krunal Shah
  • 1,438
  • 1
  • 17
  • 29
0

If you want to get string value

String id = cursor.getString( cursor.getColumnIndex("name") ); // id is column name in db
or

String id = cursor.getString( cursor.getColumnIndex(0)); 

If you want to get Integer value

String id = cursor.getInt( cursor.getColumnIndex("id") ); // id is column name in db
or

String id = cursor.getInt( cursor.getColumnIndex(0)); 
Hoque MD Zahidul
  • 10,560
  • 2
  • 37
  • 40
0

In Android Studio 3.4.1 (I use Kotlin but it does not make any difference here), I've discovered a very odd behaviour.

For instance:

Cursor c = db.rawQuery("Select IDH, ID, NOME, CONTEUDO from CalcHome 
           Inner Join Calcs using(id)", null)

The column names was registered in a rigid way, independent of case of field names in Select. The array component c.columnNames[0] is Idh not IDH

So

int a = c.getInt(c.getColumnIndex("IDH")) // gives a runtime error.

But

int a = c.getInt(c.getColumnIndex("Idh")) // works!
Paulo Buchsbaum
  • 2,471
  • 26
  • 29