Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

Move the Cursor at First record like:

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

if (mCursor != null) {
        mCursor.moveToFirst();
 String data = cursor.getString(cursor.getColumnIndex("data"));
    }
 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 != null) {
       cursor.moveToFirst();
       if (cursor.getCount() > 0) {
           while (cursor.isAfterLast() == false) { //You need to check if cursor doesnot contain last row 
              String data = cursor.getString(cursor.getColumnIndex("data"));
              cursor.moveToNext();
           }
       }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top