Search code examples
androidsqliteandroid-cursor

How to retrieve data from cursor?


public String getSum(String code) 
{
        SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor =db.query(TABLE_OWNER, new String[] { KEY_SUM }, KEY_CODE + "=?", new String[] { code }, null, null, null, null);
    String data = cursor.getString(cursor.getColumnIndex("data"));
        return data;
    }

I would like to get the data "KEY_SUM", but it is failure to get it. How can I do so ?

public String getSum(String code) {
    SQLiteDatabase db = this.getReadableDatabase();


    Cursor cursor =db.query(TABLE_OWNER, new String[] { KEY_SUM }, KEY_CODE + "=?", new String[] { code }, null, null, null, null);

    String data = "0";
    if (cursor.moveToFirst()) 
    { 
        data = cursor.getString (cursor.getColumnIndex (KEY_SUM));
    }
    return data;
}

After I implement like that I can't get value too. I only get the 0.


Solution

  • You need to write moveToFirst(); before fetching data from cursor, like below,

    public String getSum(String code) 
    {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_OWNER, new String[] { KEY_SUM }, KEY_CODE + "=?", new String[] { code }, null, null, null, null);
    
        if ( cursor.getCount() > 0 )
        {
            cursor.moveToFirst();                                            // Add this line
            String data = cursor.getString(cursor.getColumnIndex("data"));
            return data;
        }
        return null;
    }