Search code examples
javaandroidandroid-listviewsimplecursoradapter

App Closes with this error - requesting column name with table name


I'm trying to use a ListAdapter to display the results of a Cursor. According to my logs everything is returned the correct results until it gets to this point

    ListAdapter adapter = new SimpleCursorAdapter(this,R.layout.cattle_layout,
            c,new String[]{"c.animal_id, c.eartag"},new int[]{R.id.TextView_cattleId,R.id.TextView_earTag});

At that point, the program throws an exception with the above mentioned message and it then names the two fields I want to display - from that point on it's next a java.lang.Exception and then references to the AbstractCursor.getColumnIndexOrThrow

There has to be a problem with the 'new String[] creation", but I've searched and can't find anything.

Suggestions would be appreciated.

Cursor Creation is

        String asColumnsToReturn[] ={
    "tbl_cattle._id",
    "tbl_cattle.animal_id",
    "tbl_cattle.eartag"};

    Cursor c = mDatabase.query(TABLE_CATTLE, asColumnsToReturn,"type_of_animal=?", new String[]{targetType},null, null, null, null);
    Log.i(DEBUG_TAG, "Record Count " + c.getCount() + " Columns: " + c.getColumnCount());

My Log gives me the correct count for the where clause, the correct data is in the records


Solution

  • try

    new String[] { "COLUMNNAME_ANIMAL_ID", "COLUMNNAME_EARTAG" }
    

    where those two strings are just what they sound like. also you should really use static strings for column names. within your database define them once like :

    public final static String COLUMNNAME_ANIMAL_ID = animalId; // where animalId is how the SQL column will be named.
    

    and call that stuff from everywhere you need it with DatabaseClass.COLUMNNAME_ANIMAL_ID

    in this example you would then use:

    new String[] { DatabaseClass.COLUMNNAME_ANIMAL_ID, DatabaseClass.COLUMNNAME_EARTAG }
    

    this way you a) can be sure you have no spelling errors in your SQL and b) can change column/table/DB names as quick as 1,2,3 - no matter where you used them.