Runtime error ( IllegalArgumentException) when using SimpleCursorAdapter - column '_id' does not exist

后端 未结 1 1020
有刺的猬
有刺的猬 2021-01-27 19:55

I try to get some db values and display them in a listview.

Here is my code:

public class SearchCustomer extends Activity{    

private DBCreater dbHelpe         


        
相关标签:
1条回答
  • 2021-01-27 20:29

    Per the documentation for CursorAdapter, of which SimpleCursorAdapter is a subclass :

    The Cursor must include a column named "_id" or this class will not work.

    If your table already has a column named "_id", then just include this in the query's projection (the requested columns).

    String selectQuery = "select _id, customer_name, ... from Customer";
    

    If your table doesn't have an "_id" column, you can instead alias the "rowid" that all SQLite tables have by default (excepting those explicitly created without one).

    String selectQuery = "select rowid as _id, customer_name, ... from Customer";
    

    The same can be done even if you're not using raw SQL. For example, in a query() call:

    mCursor = db.query("Customer", new String[] {"rowid as _id", "customer_name", ...}, ...);
    

    You can, of course, alias another column you might already have, if it's equivalent to an "_id". Do note, though, that you must use the alias name - i.e., "_id" - with the Cursor, should you be manually retrieving values from it.

    0 讨论(0)
提交回复
热议问题