Domanda

I'm trying to use a SimpleCursorAdapter to populate a ListView. However, constructing the SimpleCursorAdapter has my compiler throw me an exception. The strangest thing is that I've used almost the exact same structure to great success earlier in my application. This is what I'm having problems with:

cursor = db.rawQuery("SELECT "      + DatabaseHelper.KEY_AMOUNT
                            + ", "      + DatabaseHelper.KEY_DATE
                            + " FROM "  + DatabaseHelper.TABLE_HISTORY
                            + " WHERE " + DatabaseHelper.KEY_ID
                            + "=?",
                        new String[]{""+tenantId});
cursor.moveToFirst();

try {

    tryAdapter = new SimpleCursorAdapter(
            this, 
            R.layout.history_item, 
            cursor,
            new String[] {DatabaseHelper.KEY_AMOUNT, DatabaseHelper.KEY_DATE},
            new int[] {R.id.historyPaymentColumn, R.id.historyDateColumn});
    } catch (Exception e) {
        e.printStackTrace();
    }

And here's the instance of the SimpleCursorAdapter that I use earlier in the application (the one that works):

cursor = db.rawQuery("SELECT _id, firstName, lastName, phone FROM phonebook", null);
adapter = new SimpleCursorAdapter(
            this,
            R.layout.phonebook_item,
            cursor,
            new String[]{"firstName", "lastName", "phone"}, 
            new int[] {R.id.firstName, R.id.lastName, R.id.phone});
setListAdapter(adapter);

Can anyone tell me what exactly the difference between these two that causes the tryAdapter to fail but leave the adapter instance untouched?

È stato utile?

Soluzione

I cant be sure since you haven't posted your Logcat output, but looking at the column names in your selection, it seems that you haven't included a column named _ID in your projection. Any Cursor you pass to a CursorAdapter must include a column named "_id" or the class will not work.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top