How to get column value from sqlite cursor?

馋奶兔 提交于 2019-11-29 16:43:48

问题


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?


回答1:


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



回答2:


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




回答3:


  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);




回答4:


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)); 



回答5:


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!


来源:https://stackoverflow.com/questions/9412040/how-to-get-column-value-from-sqlite-cursor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!