开发者

android sqlite exception:java.lang.IllegalArgumentException: column '_id' does not exist

开发者 https://www.devze.com 2023-01-06 21:55 出处:网络
I created a sql lite database with the following columns: static final String dbName=\"demoDB\"; static final String tableName=\"Employees\";

I created a sql lite database with the following columns:

static final String dbName="demoDB";
    static final String tableName="Employees";
    static final String colID="EmployeeID";

then

public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE "+tableName+" ("+colID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
                colName+" TEXT, "+colAge+" Integer);");
    }

I want to select all the records in the database like this and display them in a gridview:

SQLiteDatabase db=this.getWritableDatabase();
         Cursor cur= db.rawQuery("Select "+colName+", "+colAge+" from "+tableName, new String [] {});

String [] from=new String []{DatabaseHelper.colName,DatabaseHelper.colAge};
    开发者_JAVA百科        int [] to=new int [] {R.id.colName,R.id.colAge};
            SimpleCursorAdapter sca=new SimpleCursorAdapter(this,R.layout.gridrow,c,from,to);


        GridView grid=(GridView)findViewById(R.id.grid);
        grid.setAdapter(sca);

but i receive the following exception:

java.lang.IllegalArgumentException: column '_id' does not exist.

the db table does not have a column with name '_id'

so what is wrong with this code

Thanks


a workaround to this problem is to use select statment like this

select EmpId as _id

cause the adapter requires a column with the name _id as you said

thanks


When using an adapter, your Table must always have the Primary Key Column named as "_id"

Just change

static final String colID="EmployeeID"; 

to

static final String colID="_id"; 

Cheers!


CursorAdapters require an INTEGER PRIMARY KEY column named _id (available from BaseColumns).


Try this way

SELECT  _ID as _ID,_ID as _id , cont_type ,.... FROM  DATABASE_TABLE ;

When _ID only ,Message is column '_id' does not exist.
When _id only ,Message is column '_ID' does not exist.


I tried _id (lower case) instead of _ID (Uppercase) solves the problem. Make sure to recreate the DB once again with _id (lowercase)

Thank you very much


If you loading your database from assets: After you have changde your id to _id in the database base table, and your loading it from assets folder that you uninstall the app first, otherwise you will be using your old database.

0

精彩评论

暂无评论...
验证码 换一张
取 消