samedi 7 novembre 2015

Android Studio - Cursor.getString() throwing exception

I'm new to Android Studio and this is my first application in general where I'm working with database connectivity, so I may just be fundamentally misunderstanding how the cursor works.

I'm querying my database, and tests show that the query is successful, specifically the getCount() method returns 2 as the number of rows the cursor object contains. However when I call the getString() method it throws an exception instead of returning the column data.

Anything pop out right away that could be wrong with this code?

    public void GetFacts(View v) {

    Cursor cursor = database.query(ExternalDbOpenHelper.TABLE_NAME,
            null, "valueRange = 'MEDIUM'", null, null, null, null);

    // Log number of rows from query
    Log.d("CursorTest", "Row count: " + cursor.getCount());

    try {
        // get data from "factName" column of database
        String columnName = cursor.getColumnName(0);
        Log.d("CursorTest", "Column Name: " + columnName);

        String data = cursor.getString(cursor.getColumnIndex(columnName));

    } catch(Exception e) {
        // Log exception thrown
        Log.d("CursorTest", "Error getting data: " + e.getMessage());

    }
}

And the log gives me the following:

D/CursorTest: Row count: 2

D/CursorTest: Column Name: factName

D/CursorTest: Error getting data: Index -1 requested, with a size of 2

Aucun commentaire:

Enregistrer un commentaire