I would also just hide the splash screen once the db started rather than setting the root page. I’m not saying that’s necessarily the problem, but seems like that might be a better way.
I would suggest that you use the Ionic Native SQLite plugin, which is all promisified for you: https://ionicframework.com/docs/native/sqlite/. Also if you don’t have huge amounts of data or complex relations the Ionic Storage plugin is simpler to work with. Depends on your use case.
I would also recommend that you do not use transaction()
, as it is about to be removed from the plugin: https://github.com/litehelpers/Cordova-sqlite-storage#important-api-deprecation-notice.
All database calls should really live in a service, rather than right in your page.
I would do (and have previously done) something like this (disclaimer I’ve never tried to access sqlite_master, but I assume it works fine here, certainly any tables you create will work. I also have not run this code, just made it up, might need minor tweaks):
@Injectable
export class DatabaseService {
constructor(private sqlite: SQLite) {}
private initializeDatabase(): Promise<SQLiteObject> {
return this.sqlite.create({
name: 'test',
location: 'default'
});
}
async getSqlMasterCount(): Promise<number> {
const db = await this.intializeDatabase();
const results = await db.executeSql('SELECT count(*) FROM sqlite_master');
return results.rows.items(0);
}
}
Then back in your page:
export class MyApp implements OnInit {
rootPage:any = HomePage;
constructor(
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
databaseService: DatabaseService
) {}
async ngOnInit() {
try {
await this.platform.ready();
await this.databaseService.getSqlMasterCount();
this.splashScreen.hide();
} catch(error) {
console.log('error during initialization');
}
}
I hid the splash screen rather than setting the root. If you for some reason really need to reset the root instead of hiding the splash screen, you should use the NavController to set the root: https://ionicframework.com/docs/api/navigation/NavController/#setRoot
this.navController.setRoot(HomePage)
I also use OnInit to do the initialization code instead of the constructor, but you could just call your method from the constructor instead if you wanted.
Finally, if you do set the root rather than hiding the splash screen, be sure to show a loading spinner at least, otherwise your user will think the app is frozen/hanging.