How I can implement the SQLite Plugin for my ionic project


#1

Hello there!

I’m really new to AngularJS and ionic but in this week I learned a lot.
My biggest problem is to implement the SQLite plugin in my ionic project. It doesn’t works I don’t know why. I tried this week to install this plugin. I spend a lot of time and searched the web and tutorial and I show you what I tried already.

I tried these tutorials


and this

and this

Nothing worked.
I got this Error message:

Uncaught TypeError: Cannot read property ‘openDatabase’ of undefined

In some Blog’s and pages like here http://stackoverflow.com/questions/28244311/typeerror-cannot-read-property-opendatabase-of-undefined

The people say it can be that the ng-cordova is not implemented or I can’t use the SQLite Plugin running on a Webbrowser. I tested in IOS and Android but it don’t work. I downloaded the latest ng-cordova and used in my index.html above the cordova.js

If I add this code

if(window.cordova) {
// App syntax
db = $cordovaSQLite.openDB(“populated.db”);
} else {
// Ionic serve syntax
db = window.openDatabase(“myapp.db”, “1.0”, “My app”, -1);
//
In the Webbrowser works fine but on Android and IOS it doesn’t.

And yes I tried this app syntax for IOS or Android:
db = $cordovaSQLite.openDB({name: “my.db”});

Don’t worked!

I don’t wanna put all my code to this topic so I uploaded to Github.
I hope someone can say what I did wrong.

I created one time the query in the the app.js and I created a controller called StartCtrl to run the insert method.

GitHub Link:

Thanks for your help!


#2

you need to wait until cordova and your device is ready
wrap all codeblocks that are using plugins or native components in $ionicPlatform.ready to ensure that everything is up and running.
http://ionicframework.com/docs/api/service/$ionicPlatform/


#3

Men, I cried. I cried really. I can’t trust my eyes it works!!! I don’t believe that. THANK YOU MEN THAAAAANK YOU!!!


#4

thank youuuuuu!!!
add below code according to your platform… it works

if(isAndroid){
// Works on android but not in iOS
_sqlLiteDB = $cordovaSQLite.openDB({ name: “testDB.db”, iosDatabaseLocation:‘default’});
} else{
// Works on iOS
_sqlLiteDB = window.sqlitePlugin.openDatabase({ name: “testDB.db”, location: 2, createFromLocation: 1});
}