I'm using a SQLite database on Android and I need a particular value from the table. I have a DataBaseHelper
class.
private static final String TABLE_NAME = "my_task";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String COL3 = "status";
private static final String COL4 = "rec";
I have to get the value of column rec
for the given name
(it's either 0 or 1). I have this function to do the task:
public Cursor getRec(String task) {
SQLiteDatabase db = this.getWritableDatabase();
String q = "SELECT " COL4 " FROM " TABLE_NAME " WHERE " COL2 " = ?";
Cursor data = db.rawQuery(q, new String[] { task });
return data;
}
I don't know how to get the required value from this returned cursor. I'm new to this, so please help me with this.
CodePudding user response:
The function getRec()
returns a Cursor
and you can call it like:
Cursor c = getRec("John");
Then you must check if the cursor contains any rows and if it does you can extract the value of the 1st row:
String rec;
if (c.moveToFirst()) rec = c.getString(0);
c.close();
You can check the value of the variable rec
:
- if it is
null
then'John'
was not found in the table - if it is not
null
then the variablerec
contains the value of the columnrec
of the table.
I assume that you expect only 1 row as the result of your query.
If you expect more than 1 rows then use a loop that collects all the rec
s returned in a list:
ArrayList<String> list = new ArrayList();
while (c.moveToNext()) {
list.add(c.getString(0));
}
c.close();