Open db before load init view

My start view must show a list of elements from the sqlite db, have managed to select and insert from the db and the way i open the db is like in this example https://blog.nraboy.com/2014/11/use-sqlite-instead-local-storage-ionic-framework/.

rrApp.run(function($ionicPlatform, $state, $cordovaSQLite) {
$ionicPlatform.ready(function() {
	
	if (window.cordova && window.cordova.plugins.Keyboard) {
		cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
	}
	if (window.StatusBar) {
		StatusBar.styleDefault();
	}
	
	db = $cordovaSQLite.openDB("my.db");
	$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS EVENTS (ID integer primary key, NAME text)");
   	$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS TASKS (ID integer primary key, EVENT_ID integer, NAME text)");   	 
   	   	
});

the problem i have is when i execute $cordovaSQLite .execute(db,“SELECT * FROM TABLE”) it always return this error:
TypeError: Cannot call method ‘transaction’ of null

how can i succesfully open the db before the controller try to retrieve something from it?

1 Like

That’s because ionicPlatform ready sometimes don’t work as intended.

Instead you should use default Cordova:

document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
function onDeviceReady() {
  var db = window.sqlitePlugin.openDatabase({name: "my.db"});
  // ...
}

If you want to be sure that the db is opened before any view is shown or something like this
–> add a root state to your app and use uiRouters resolve property where you open the dbconnection

I apologise for the delay, after i tried using both of your aproaches and getting no results (maybe because i didnt do it right), I solved this by using :

db = $cordovaSQLite.openDB(“my.db”);
$cordovaSQLite.execute(db, “CREATE TABLE IF NOT EXISTS EVENTS (ID integer primary key, NAME text)”);
$cordovaSQLite.execute(db, “CREATE TABLE IF NOT EXISTS TASKS (ID integer primary key, EVENT_ID integer, NAME text)”);
$rootScope.$broadcast(‘dbInitialized’);

and adding this in the controller

var scope = $rootScope.$new();
scope.$on(‘dbInitialized’, function() {
$scope.loadRoutines();
})

I’m not sure its the best way but Its working, do you think this is a bad way to do iy?
thank you both!

1 Like

I’m solved this problem as well:


app.js:

$ionicPlatform.ready(function () { 
        db = $cordovaSQLite.openDB("my.db");
        alert("HERE 1");
    });

controller:

$ionicPlatform.ready(function () {
    alert("HERE 2");
    // SELECT 
});

Thus alert 1 comes before alert 2

1 Like

May not be the best, but at least your works! Thanks mate! :slight_smile: