Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get column value from sqlite cursor?

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?

like image 899
Chandrapal Yadav Avatar asked Feb 23 '12 11:02

Chandrapal Yadav


People also ask

What is cursor moveToNext?

moveToNext move the cursor to the next row. and c.getString(0) will always give you the first column if there is one.

Which function do you call from a cursor object to get the number of rows in the cursor object?

getCount. Returns the numbers of rows in the cursor.

How do I find data in SQLite?

To Search for the values define edit text and implement text watcher in database enter a query as shown below: editText. addTextChangedListener(new TextWatcher(){ Cursor cusror; cursor=db. rawQuery("SELECT * FROM "+ DB_NAME + " WHERE " + DB_NAME.id + " = " + DB_NAME.Id + " AND " + DB_NAME.


3 Answers

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
like image 193
Lucifer Avatar answered Oct 01 '22 14:10

Lucifer


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

like image 20
Rafael Nobre Avatar answered Oct 01 '22 14:10

Rafael Nobre


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

like image 21
Krunal Shah Avatar answered Oct 01 '22 14:10

Krunal Shah