0

I am working with SQLite Database in android studio. My onCreate code:

   @Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_MOODS_TABLE = "CREATE TABLE " + TABLE_NAME_MOODS + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_MOODS + " TEXT NOT NULL)";
    db.execSQL(CREATE_MOODS_TABLE);
}

and my Queries:

@Override
public Uri insert(@NonNull Uri uri,  ContentValues values) {

    final SQLiteDatabase db = mMindsDbHelper.getWritableDatabase();
    final SQLiteDatabase db2 = mMindsDbHelper.getReadableDatabase();
    long id = db.insert(TABLE_NAME_MOODS, null, values);
    String query = "SELECT * FROM "+ TABLE_NAME_MOODS;
    Cursor returnCursor;
    returnCursor = db2.rawQuery(query, null);
    return null;
}

For debugging purpose I have added select query in this place. when debugger hits these points, return id of db.insert returns some value(i.e. id of new inserted values). But select query doesn't return anything useful(it returns mCount as -1). I have tries following query also but result is same.

  returnCursor = db.query(TABLE_NAME_MOODS,
                    projection,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder);

Where is the problem.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Amit Sinha
  • 566
  • 7
  • 22
  • 1
    You obtain a cursor `returnCursor` but you don't actually do anything with it. Have you tried iterating this cursor? – Tim Biegeleisen Oct 21 '17 at 10:34
  • @TimBiegeleisen In debug windows it shows the all details of returnCursor. And it returns only column names, and mCount as -1; – Amit Sinha Oct 21 '17 at 10:45
  • @EnigmaticMind cursor until you do something with it will show this. Try adding line `returnCursor.getCount();` and then move to return null; in debug. You will then see the count. You could also try `returnCursor.movetoFirst()` as a line (etc). You may also find this useful [Are there any methods that assist with resolving common SQLite issues?](https://stackoverflow.com/questions/46642269/are-there-any-methods-that-assist-with-resolving-common-sqlite-issues) – MikeT Oct 21 '17 at 11:07
  • @MikeT Yes bro, you are right. Thanks for help. – Amit Sinha Oct 21 '17 at 11:19

1 Answers1

1

But select query doesn't return anything useful(it returns mCount as -1)

rawQuery() compiles a query but does not execute it. Hence the count is -1 for a query that has not been executed yet. The same applies to query() since it's essentially just a wrapper for rawQuery(). A query that was executed and matched no records would have its count set to 0.

To actually execute at least one step of a query compiled with rawQuery(), you need to call one of the moveTo...() methods on the returned Cursor. For example, moveToFirst().

laalto
  • 150,114
  • 66
  • 286
  • 303