RedLeader
RedLeader

Reputation: 657

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!!

Upvotes: 4

Views: 1769

Answers (2)

woodshy
woodshy

Reputation: 4111

First of all try to query this way:

String args[] = new String[]{"0"};

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

If this not helps check your db with external tool if you query return rows there.

Upvotes: 2

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

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.

Upvotes: 2

Related Questions