Reputation: 157
I have a class DatabaseHandler. I have overridden the onCreate(SQLiteDatabase db) method with the following code :
String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_SONG + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
SONG_TITLE + " TEXT," + ARTIST_NAME + " TEXT," + GENRE + " TEXT," +
SONG_PATH + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
but I found that there were extra items getting appended to the TABLE_SONG everytime I opened the emulator as a result of which even though I had 6 songs in the sdcard the database showed 454 songs. This forced me to drop the table with a thought of recreating it again. But now I am stuck that the table could not be found or rather is not getting created. Shouldnt it be that the onCreate() method should get called everytime when I create an object of this class?
Upvotes: 1
Views: 1100
Reputation: 877
I agree with waqas please find sample code below
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME
+ ... ) ";
db.execSQL(CREATE_TABLE);}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
EDIT USE of onUpgrade()
It is called when you construct a SQLiteOpenHelper with version newer than the version of the opened database. What to do depends on the changes in the database that are made between the old and new versions. The only case when you don't drop a changed table is when the change is noting more than an added column. Then you can use ALTER TABLE statement to add the new column to the table signature.
Upvotes: 0
Reputation: 48272
onCreate
will not be called if the database has already been created, such as during the previous time you have run your application.
Either uninstall your app and install again - it will remove the db files as well
or increment your db version this will result in onUpgrade
being called. In onUpgrade
you can drop all your tables and call onCreate
Upvotes: 0
Reputation: 68187
Referring to SQLiteOpenHelper
implementation, the onCreate
method is called only once when it doesn't find the database file, causing it to create one. Later, onUpgrade
is called whenever the database version number is found to be incremented.
To solve your problem quickly, simply uninstall and then install the app again. This will cause your database to go away, so allowing onCreate
to be called once again.
Upvotes: 1