jonnie
jonnie

Reputation: 12680

How do I use the ngCordova sqlite service and the Cordova-SQLitePlugin with Ionic Framework?

I have been trying to incorperate sqlite into a simple Ionic app and this is the process I have been following:

 ionic start myApp sidemenu

Then I install the sqlite plugin:

ionic plugin add https://github.com/brodysoft/Cordova-SQLitePlugin

and ngCordova

bower install ngCordova

this gave me the following options: Unable to find a suitable version for angular, please choose one: 1) angular#1.2.0 which resolved to 1.2.0 and is required by ngCordova#0.1.4-alpha 2) angular#>= 1.0.8 which resolved to 1.2.0 and is required by angular-ui-router#0.2.10 3) angular#1.2.25 which resolved to 1.2.25 and is required by angular-animate#1.2.25, angular-sanitize#1.2.25 4) angular#~1.2.17 which resolved to 1.2.25 and is required by ionic#1.0.0-beta.13Prefix the choice with ! to persist it to bower.json

I picked option 3) and I included the scripts in the file as follows:

<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>

I then added a controller to the search view:

.controller('SearchCtrl', function ($scope, $cordovaSQLite){
  console.log('Test');
   var db = $cordovaSQLite.openDB({ name: "my.db" });

        // for opening a background db:
        var db = $cordovaSQLite.openDB({ name: "my.db", bgType: 1 });

        $scope.execute = function() {
          console.log('Test');
          var query = "INSERT INTO test_table (data, data_num) VALUES (?,?)";
          $cordovaSQLite.execute(db, query, ["test", 100]).then(function(res) {
            console.log("insertId: " + res.insertId);
          }, function (err) {
            console.error(err);
          });
     };
})

This caused the error:

> TypeError: Cannot read property 'openDatabase' of undefined
>     at Object.openDB  (http://localhost:8100/lib/ngCordova/dist/ng-cordova.js:2467:36) 

Next I tried manually including the SQLitePlugin.js by: copying from plugins/com.brodysoft.sqlitePlugin/www to main www/ and adding it to the index.html page

I tried including before everything:

 <script src="SQLitePlugin.js"></script>
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>

I get Error ReferenceError: cordova is not defined so I then tried including it after the cordova.js script but still get the same error

would really appreciate the help in case it is relevant, these are the current versions of Cordova and ionic I am using:

ionic --version  1.2.5
cordova --version 3.5.0-0.2.7

and this is the generated bower.json

{
  "name": "myApp",
  "private": "true",
  "devDependencies": {
    "ionic": "driftyco/ionic-bower#1.0.0-beta.13"
  }
}

and my package.json:

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "myApp: An Ionic project",
  "dependencies": {
    "gulp": "^3.5.6",
    "gulp-sass": "^0.7.1",
    "gulp-concat": "^2.2.0",
    "gulp-minify-css": "^0.3.0",
    "gulp-rename": "^1.2.0"
  },
  "devDependencies": {
    "bower": "^1.3.3",
    "gulp-util": "^2.2.14",
    "shelljs": "^0.3.0"
  }
}

Upvotes: 19

Views: 30748

Answers (4)

maninak
maninak

Reputation: 2726

For later Ionic versions (Ionic 2+):

The best way to handle persistent storage with Ionic is using ionic-storage.

Ionic Storage is a package created and maintained by the ionic team to abstract development from the specifics of each browser or platform and automatically use the best storage solution available.


1. Installing Dependencies

In your case for SQLite you need to first install the dependencies for both Angular and Cordova:

npm install @ionic/storage --save

and

cordova plugin add cordova-sqlite-storage --save

Then edit your NgModule declaration in src/app/app.module.ts to add IonicStorageModule as an import:

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
  declarations: [...],
  imports: [
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot({
      name: '__mydb',
      driverOrder: ['indexeddb', 'sqlite', 'websql'],
    })
  ],
  bootstrap: [...],
  entryComponents: [...],
  providers: [...],
})
export class AppModule { }

2. Inject Storage into your component

import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public storage: Storage) {}
}

3. Storing data in SQLite

Whenever you access storage, make sure to always wrap your code in the following:

storage.ready().then(() => { /* code here safely */});

3.1 Saving a key-value pair

storage.ready().then(() => {
    storage.set('some key', 'some value');
});

3.2 Retrieving a value

storage.ready().then(() => {
  storage.get('age').then((val: string) => {
      console.log('Your age is', val);
  });
});

3.3 Deleting a key-value pair

storage.ready().then(() => {
    storage.remove('key').then((key: string) => { /* do something after deletion */})
});

Upvotes: 1

Luis Antonio Pestana
Luis Antonio Pestana

Reputation: 1009

In Ionic 2, I am using the following code.

constructor(platform: Platform) {
platform.ready().then(() => {



  if(platform.is("cordova")){
    //USE Device
  }
  else {
    //USE Browser
  }



  StatusBar.styleDefault();
});

Upvotes: 1

junior
junior

Reputation: 808

If someone still got an error when trying to run it in a browser, try this one:

if (window.cordova) {
      db = $cordovaSQLite.openDB({ name: "my.db" }); //device
    }else{
      db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser
    }

Upvotes: 43

jonnie
jonnie

Reputation: 12680

So Turns out that it is because Cordova is platform specific and doesn't work when you run ionic serve

I was able to run the same code on an android device with out issue when I built and deployed.

Update

you can replace the cordova plugin with window to use the websql databases so instead of sqlitePlugin.openDatabase() you can use window.openDatabase()

Upvotes: 8

Related Questions