Search code examples
javaandroidsqldatabaseandroid-cursor

Android SQLLiteDataBase cursor returning 0 rows


For the life of me, I can't get the cursor to return any data. I've verified that their is data in the database and my insertions are working. The official error is:

CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

Top level declarations:

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx) 
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
    this.db = this.DBHelper.getWritableDatabase();
}

My function:

public String getRandomEntry()
    {
    int rand;
    Random random = new Random();
    int numEntries = (int)this.getCount();

    if(numEntries == 0)
        return "ERROR: Database is empty.";
    rand = random.nextInt(numEntries);

    Cursor cursor = DBHelper.getWritableDatabase().rawQuery(
            "SELECT * FROM " + DATABASE_TABLE 
            + " WHERE " + COLUMN_A + " = " + 0, null);

    Log.i("numEntries", Integer.toString(numEntries));
    Log.i("rand", Integer.toString(rand));
    Log.i("cursor", Integer.toString(cursor.getCount()));

    cursor.moveToFirst();
    return cursor.getString(0);
}

I've also tried grabbing the cursor as such:

Cursor cursor = db.rawQuery(
            "SELECT * FROM " + DATABASE_TABLE 
            + " WHERE " + COLUMN_A + " = " + 0, null);

Please give me your thoughts! Thank you!!


Solution

  • Nothing seems random here at all. It appears that you are looking for column_a with a value of 0 every time.

    I would assume that column_a has nothing with a value of 0.