Oncreate() Of Roomdatabase.callback() Was Not Called After A Successful Call To .build()
Solution 1:
The reason why OnCreate isn't being called is because it is only called once when the database is first created and then never again as long as the database exists.
If you delete the App's data or uninstall the App and then rerun it you will see that onCreate is then called.
e.g.
privatevoidBuildDatabase() {
RoomDatabase.Builderroombuilder= Room.databaseBuilder(this, Database.class,"mydb");
roombuilder.addCallback(newRoomDatabase.Callback() {
@OverridepublicvoidonCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
Log.d("ONCREATE","Database has been created.");
}
@OverridepublicvoidonOpen(@NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
Log.d("ONOPEN","Database has been opened.");
}
});
mRoomDB = (Database) roombuilder.build();
}
After deleting the App's data results in :-
2018-12-20 06:36:23.045 2271-2287/so53839431.so53839431roomrelationship D/ONCREATE: Database has been created.
2018-12-20 06:36:23.055 2271-2287/so53839431.so53839431roomrelationship D/ONOPEN: Database has been opened.
Solution 2:
Oncreate
method is called once the database is created. Room database is abstraction of SQLiteOpenHelper. Database created when getReadableDatabase() or getWriteableDatabase() called. So until some concrete operation is performed, such as invoking a @Dao method that hits the database, database will not be created.
To solve the issue you should apply one of below options.
Perform some operations including @delete, @insert or @update
or
Delete app data in phone's settings before you uninstall an app
or
Delete your db files manually (device file explorer → data → data →
com.company.yourapp
→ databases on Android Studio).or
Call the following code in your project:
publicvoiddeleteDatabaseFile(String databaseName) { Filedatabases=newFile(getApplicationInfo().dataDir + "/databases"); Filedb=newFile(databases, databaseName); if (db.delete()) Timber.d("Database deleted successfully"); else Timber.d("Failed to delete database"); }
Post a Comment for "Oncreate() Of Roomdatabase.callback() Was Not Called After A Successful Call To .build()"