How to get column value from sqlite cursor?

*爱你&永不变心* 提交于 2019-11-30 11:12:37

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

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

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

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

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