xyz rety xyz rety - 5 months ago 17
MySQL Question

IllegalArgumentException: column '_id' does not exist?

I am trying to use

CursorAdapter
with
ListView
, but logcat shows this message:


"IllegalArgumentException: column '_id' does not exist"


This belongs from main activity:

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);


This belongs from database:

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;

}
}

Answer

Just change id to _id. SimpleCursorAdapter needs a column with this name.

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

If you don't want to rename your column name the you will have to use alias in your select query.