storesafe / cordova-sqlite-storage

A Cordova/PhoneGap plugin to open and use sqlite databases on Android, iOS and Windows with HTML5/Web SQL API
Other
2.15k stars 715 forks source link

openDB don't work in android #598

Open PterPmnta opened 7 years ago

PterPmnta commented 7 years ago

I try to create a new project, but don't work the plugin, this is the error:

ionic.bundle.js:26794 TypeError: Cannot read property 'openDatabase' of undefined
    at Object.crearDB (app.js:48)
    at new networkCtrl (app.js:30)
    at Object.invoke (ionic.bundle.js:17995)
    at $controllerInit (ionic.bundle.js:23397)
    at nodeLinkFn (ionic.bundle.js:22335)
    at compositeLinkFn (ionic.bundle.js:21703)
    at nodeLinkFn (ionic.bundle.js:22387)
    at compositeLinkFn (ionic.bundle.js:21703)
    at compositeLinkFn (ionic.bundle.js:21706)
    at publicLinkFn (ionic.bundle.js:21583)(anonymous function) 

This is my code

angular.module('starter', ['ionic', 'ngCordova'])
    .run(startApp)
    .controller('networkCtrl', networkCtrl)
    .factory('databaseFtr', databaseFtr);

startApp.$inject = ['$ionicPlatform'];

function startApp($ionicPlatform) {

    $ionicPlatform.ready(function() {

        if (window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            cordova.plugins.Keyboard.disableScroll(true);
        }

        if (window.StatusBar) {
            StatusBar.styleDefault();
        }

    });

}

networkCtrl.$inject = ['$scope', 'databaseFtr'];

function networkCtrl($scope, databaseFtr) {
    databaseFtr.crearDB();
}

databaseFtr.$inject = ['$cordovaSQLite'];

function databaseFtr($cordovaSQLite) {

    return {

        crearDB: function() {

            var db;

            db = $cordovaSQLite.openDB({
                name: "mydata.db",
                location: 'default'
            });

        }

    }

}

Image show the plugin install

plugin db

brodycj commented 7 years ago

The problem is that your app does not wait for the deviceready event before attempting to open a database. This is a common problem with Angular controllers and I already documented this as a pitfall.

I will document the "cannot read property" error as a sign of this pitfall when I get a chance.

PterPmnta commented 7 years ago

@brodybits Thanks for all, now work perfect, sorry, i will to know if exists one way the create the databse without click function xecute a query

brodycj commented 7 years ago

I recommend that you look at the suggestion in https://github.com/driftyco/ng-cordova/issues/8#issuecomment-48703042 by @romgar:

An another way is to initialize angular dynamically when cordova is ready.

window.ionic.Platform.ready(function() {
   angular.bootstrap(document, ['<your_main_app']);
});

Works like a charm.