Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting one row from sqlite database using rawQuery and rowid in Android

I've created an external SQLite database that looks something like this: image of a few rows of a database

What I want to do in my Android application is to load all the values from one row using ROWID and put them into array. For example:

Cursor cursor = db.rawQuery("SELECT * FROM Dairy WHERE ROWID = 1", null);

This would return all the values from row 1: 51, 35, 63. However, this always returns just first value, in this case 51. Also, the cursor.getCount() always returns 1.

Here's my complete code:

db = getReadableDatabase();

Cursor cursor = db.rawQuery("SELECT * FROM Dairy WHERE ROWID = 1", null);

yData = new int[cursor.getCount()];

if (cursor.moveToFirst()) {
    for (int i = 0; i < cursor.getCount(); i++) {
        yData[i] = cursor.getInt(0);
        cursor.moveToNext();
    }
    cursor.close();
}
db.close();
like image 562
Chilcone Avatar asked Jul 10 '26 05:07

Chilcone


1 Answers

If I correctly understand you need to return value of every column from the single row. Since you select only single row and want to get value from every column you need only to get the index of every column. and next iterate through them. Here is the code how it can be done.

Cursor cursor = db.rawQuery("SELECT * FROM Dairy WHERE ROWID = 1 Limit 1", null);

if (cursor.moveToFirst()) {
    String[] columnNames = cursor.getColumnNames();
    yData = new int[columnNames.length];

    for (int i = 0; i < columnNames.length; i++) {
        // Assume every column is int
        yData[i] = cursor.getInt(cursor.getColumnIndex(columnNames[i]));
    }  
}

cursor.close();
db.close();
like image 80
ProblemSlover Avatar answered Jul 11 '26 19:07

ProblemSlover



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!