Ng-cordova sqlite plugin: TypeError: Cannot read property 'transaction' of null


#1

I am trying to get values from database using ionic, ng-cordova, sqlite but i keep getting this error:

TypeError: Cannot read property 'transaction' of null: ionic.bundle.js:19387

Here is the code:
HTML

<ion-view view-title="Search" ng-controller="AppCtrl2">
  <ion-content>
    <ion-list>
      <ion-item ng-repeat="item in resultados">
        Hello, {{item}}!
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

app.js

var db = null;

angular.module('starter', ['ionic', 'starter.controllers','ngCordova'])

.run(function($ionicPlatform,$cordovaSQLite) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
    db = $cordovaSQLite.openDB({ name: "my.db" });
    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
    query = "INSERT INTO people (firstname, lastname) VALUES (?,?)";
    $cordovaSQLite.execute(db, query, ["Firstname", "LastName"]).then(function(res) {
        console.log("INSERT ID -> " + res.insertId);
      });

  });
})

controller

.controller('AppCtrl2', function($scope,$ionicPlatform,$cordovaSQLite) {

 $ionicPlatform.ready(function() {

    function getCat() {
      var selectQuery = "SELECT * FROM people";
      $cordovaSQLite.execute(db, selectQuery).then(function(result) {
      nombres = []; 
      for(var i=0; i<result.rows.length; i++){
          nombres.push({"nombre":result.rows.item(0).firstname});
        }
      })
    }
    $scope.resultados =  getCat();       
  })

});

How can i fix it ? The error could be of because device is not yet ready ?


#2

There should be more to the exception. What line of code and what file does the error occur on?

Also, are you running this in your simulator or on a device? It will not work in your web browser.

Regards,


#3

Doesn’t he need to open db inside controller?

Btw if you want to open it in webbrowser try using this

     $ionicPlatform.ready(function() {
    	if(window.cordova) {
	        db = $cordovaSQLite.openDB({name: app.dbName , bgType: 1});
	    } else {
	        db = window.openDatabase(app.dbName , '1', 'ES Database', 5 * 1024 * 1024);
	    }
	});

#4

The error occur in controller… $scope.resultados = getCat();
I am running this app on device…
Regards,


#5

I already opened db inside $ionicPlatform.ready


#6

I had the same issue and managed to resolve it: http://stackoverflow.com/a/31457046/2842657