IllegalArgumentException:列'_id'不存在?

时间:2016-06-10 20:25:18

标签: java android mysql sql sqlite

我正在尝试将CursorAdapterListView一起使用,但logcat会显示以下消息:

  

“IllegalArgumentException:列'_id'不存在”

这属于主要活动:

ContactDatabase onbOfContactDatabase=new ContactDatabase(getBaseContext());

Cursor mCursor= onbOfContactDatabase.phoneName();

String[] fromFileName=new String[]{ContactDatabase.NAME,ContactDatabase.PHONE};
int[] toViewId=new int[]{R.id.textView5,R.id.textView6};
SimpleCursorAdapter simpleCursorAdapter;

simpleCursorAdapter=new SimpleCursorAdapter(this,R.layout.forreading,mCursor,fromFileName,toViewId,0);
 ListView myListView=(ListView)findViewById(R.id.listView);
 myListView.setAdapter(simpleCursorAdapter);

这属于数据库:

public class ContactDatabase extends SQLiteOpenHelper {
    SQLiteDatabase db;
    public static final String DATABASE_NAME="totalContact.db";
    public static final  String TABLE_NAME="mecontact";
    public static final  String NAME="name";
    public static final  String PHONE="phone";


    public ContactDatabase(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL("create table mecontact" +
                    "(id integer primary key autoincrement, name text, phone text)");
        }catch(android.database.SQLException e){
                System.out.println("table create nhi ho rha");
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS mecontact");
        onCreate(db);
    }

    public void insertContact(String nam,String mob){

        db=this.getWritableDatabase();
        ContentValues contentValues=new ContentValues();

        contentValues.put(NAME,nam);
        contentValues.put(PHONE,mob);

        db.insert(TABLE_NAME, null, contentValues);
        db.close();
    }
    public Cursor phoneName(){

        db=this.getWritableDatabase();
        Cursor res =  db.rawQuery("SELECT * FROM mecontact ", null);
        return res;

    }
}

1 个答案:

答案 0 :(得分:1)

只需将id更改为_id即可。 SimpleCursorAdapter需要一个具有此名称的列。

db.execSQL("create table mecontact" +
                "(_id integer primary key autoincrement, name text, phone text)");

如果您不想重命名列名,则必须在选择查询中使用别名。