Search code examples
androidsqlitecursor

Retrieving PRIMARY KEY INTEGER using Cursor


I have an Activity that adds an item to a database that created. I am able to retrieve this added item by querying the database. I'm wondering why, every time I try and retrieve the Primary Key Integer associated with the row, my app crashes?

Here is my DB contract class. It implements BaseColumns, which automatically creates an _ID variable for me.

    public static class FoodList implements BaseColumns {

    public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH).build();
    public static final String TABLE_NAME = "food_table";
    public static final String ITEM_NAME = "item";
}

Here is my database Class:

public class FoodDatabase {
private SQLiteDatabase db;
private DatabaseHelper databaseHelper;
private Context context;
public static final int DB_VERSION = 2;
public static final String DB_NAME = "food_list_db";
private final String CREATE_DATABASE = "CREATE TABLE " + FoodContract.FoodList.TABLE_NAME + " ("
        + FoodContract.FoodList._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + FoodContract.FoodList.ITEM_NAME + " TEXT"
        + ");";

public FoodDatabase(Context context){
    this.context = context;
    databaseHelper = new DatabaseHelper(context);
}

public FoodDatabase openWriteableDB(){
    db = databaseHelper.getWritableDatabase();
    return this;
}

public FoodDatabase openReadableDB(){
    db = databaseHelper.getReadableDatabase();
    return this;
}

public long insertRow(ContentValues cv){
    return db.insert(FoodContract.FoodList.TABLE_NAME,null,cv);
}

public Cursor getAllRows(String[] projection, String selection, String[] selectionArgs, String sortOrder){
    return db.query(FoodContract.FoodList.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
}

public long deleteRow(long id, String whereClause, String[]whereArgs){
    return db.delete(FoodContract.FoodList.TABLE_NAME,whereClause,whereArgs);
}

public void closeDB(){
    db.close();
}

private class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_DATABASE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + FoodContract.FoodList.TABLE_NAME);
        Log.v ("DATABASE", "*********DATABASE DROPPED AND RECREATED*********");
        onCreate(db);
    }
}}

Here is what the query statement looks like within my main Fragment. The cursor is retrieved from a ContentProvider class...

        try{
        final Cursor query = getActivity().getContentResolver().query(FoodContract.FoodList.CONTENT_URI, null, null, null, null);
    }catch (Exception e){
        e.printStackTrace();
        Log.v(TAG, "****************Failed to Open**************");
    }

And here is the statement that is causing the app to crash within my Content Provider's Query method. Again, I am able to retrieve the String but not the long id. Does anyone know why?

     while(cursor.moveToNext()) {
                    Long id = cursor.getLong(cursor.getColumnIndex(FoodContract.FoodList._ID));
                    String item = cursor.getString(cursor.getColumnIndex(FoodContract.FoodList.ITEM_NAME));
                    Log.v(TAG, "*********id = " + id + " ITEM = " + item + "************");
                }

Here is the Exception

Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.

Solution

  • The issue was in this statement:

    final Cursor query = getActivity().getContentResolver().query(FoodContract.FoodList.CONTENT_URI, null, null, null, null);
    

    The 2nd parameter should not be null but rather the columns or "projection" that the returned cursor should be "looking at." In this case:

     String[] projection = {FoodContract.FoodList._ID,FoodContract.FoodList.ITEM_NAME};
    

    This String[] is used within the ContentProvider to access the database.