Zouheir lin
Zouheir lin

Reputation: 67

SQLite Exception: no such column

I am using a SQLite database and I got this this error:
Caused by: android.database.sqlite.SQLiteException: no such column: coin (code 1): , while compiling: SELECT _id, name, age, coin, log FROM person_tb1 WHERE name = ?

I have no idea why it show me this!
I have tried it before its working fine!

Here is my code:

public ArrayList<Person> getPersons (){

    persons.clear();

    SQLiteDatabase dba = this.getReadableDatabase();

    Cursor cursor = dba.query(Constants.TABLE_NAME,
            new String[]{Constants.KEY_ID, Constants.NAME, Constants.AGE , Constants.COIN , Constants.LOG},null,null,null,null,null);

    if(cursor.moveToFirst()){
        do {
            Person p = new Person();
            p.setName(cursor.getString(cursor.getColumnIndex(Constants.NAME)));
            p.setAge(cursor.getInt(cursor.getColumnIndex(Constants.AGE)));
            p.setCoin(cursor.getInt(cursor.getColumnIndex(Constants.COIN)));
            p.setLog(cursor.getInt(cursor.getColumnIndex(Constants.LOG)));
            p.setPersonId(cursor.getInt(cursor.getColumnIndex(Constants.KEY_ID)));

            persons.add(p);

        }while (cursor.moveToNext());

        cursor.close();
        dba.close();
    }
    return persons;
}

and here the select method :

 public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE = "CREATE TABLE " + Constants.TABLE_NAME + "(" +
            Constants.KEY_ID + " INTEGER PRIMARY KEY, " + Constants.NAME + " TEXT, "+
            Constants.AGE + " INT, " + Constants.COIN + " INT, " + Constants.LOG + " INT);";

    db.execSQL(CREATE_TABLE);
}

// EDIT : (OnUpgrade)

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS" + Constants.TABLE_NAME);

    onCreate(db);
}

Upvotes: 0

Views: 604

Answers (1)

Phant&#244;maxx
Phant&#244;maxx

Reputation: 38098

Wild guess: You added the column after running the app once.
If so (i have tried it before its working fine !), just unistall and reinstall your app.

OR you can simply increment your DATABASE_VERSION constant.

[EDIT]

But the second method won't work, since your current onUpgrade() method is buggy.

db.execSQL("DROP TABLE IF EXISTS" + Constants.TABLE_NAME);

Won't delete the table. And so, it won't be recreated, even.
You need to insert a space before the table name:

db.execSQL("DROP TABLE IF EXISTS " + Constants.TABLE_NAME);

Upvotes: 3

Related Questions