Deploy Ionic Framework App With Pre-Filled SQLite DB

Recently I did an article regarding SQLite as an alternative to local storage in an Ionic Framework application.  The article was a guide for using the Apache Cordova SQLite plugin for data management.  Since writing that post, a few of my readers asked me how to ship an application with a pre-populated SQLite database.

A scenario where this might be useful is if you created a lookup directory for all the employees at your company.  Let’s say you have 10,000 employees, so populating the data via a web request is probably going to take a long time.  You could ship each version of your app with the most recent lookup directory, and use an API to update it.  Since you’re only doing small changes after the initial, it is more effective than trying to download everyone.

This task is not difficult, but it could get a little confusing.  Now I’m not going to show how to do the example scenario I mentioned, but the following should put you on the right path for working with pre-populated SQLite databases.

Before we begin, I highly recommend you read the previous article I did regarding SQLite and Ionic Framework.  Without having first read it, this tutorial may be confusing.

Let’s start by creating a fresh Ionic project to work with:

Note, if you’re not using a Mac, you won’t be able to add and build for the iOS platform.

The next step is to add two Apache Cordova plugins:

These two plugins can be added by entering the following:

Because this process can get a little confusing, I’m going to re-iterate the SQLite querying portion as explained in my other article.  It won’t be near the depth of my previous article, but it will remove much of the confusion.

We need to go and download the AngularJS extension set, ngCordova, because we’ll be using it as a wrapper for our queries.  Download the latest version and copy the ng-cordova.min.js file into your www/js directory.  Now open your project’s index.html file and make it look something like the following:

Notice the two highlighted lines in the above code block.  It is very important that ng-cordova.min.js appears before the cordova.js line otherwise you’re going to end up with strange results.

Now crack open your www/js/app.js file and change your angular.module line to look like the following:

ngCordova is now set up, so it is time to worry about our pre-filled SQLite database.  In this example I’m going to use a file called populated.db and it is going to be created with the following SQL:

In addition to creating the table, it will be filled with the following data:


id firstname lastname
1 Nic Raboy
2 Maria Campos
3 Max Lynch
4 Ben Sperry

If you’re unfamiliar with making SQLite databases you can use DB Browser for SQLite, which I used when writing this guide.

OBSOLETE AS OF 02/02/2015: To include this database file into your project you must place it in your platforms/android/assets directory for Android and your Resources directory for iOS, which in my case is platforms/ios/IonicProject/Resources.  Just substitute IonicProject with whatever you called your project.  For iOS only, you’ll also need to add the file from the Resources directory into your XCode project.

UPDATE 02/02/2015: To include the database file into your project, it must live in your project’s www directory.

What comes next is going to be kept basic for simplicity, but use your imagination if you want it to be better.

Open www/js/app.js in your text editor and make it look like the following:

Take note of the highlighted lines in particular because they represent what this guide is trying to do.  The database will be copied from the assets directory to the devices protected space.  After the copy, the database will be opened using ngCordova.  Note that if the database exists in the protected space, it will not be copied again.

In our controller, we will attempt to select all records via a button press.  The button that calls our selectAll() method can be added to index.html like so:

With a little luck, you should get a print-out to your logs with all our records.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • Jay

    Hi Nick, thanks again for a great tutorial. Quick question: is there a way to view the output of console.log command when debugging on an actual device? Keep up the good work.

  • Carlos Almeida

    Hi Nic, thanks for the tutorial. Do you have another tutorial that explain how create a services with the data of a database?

    • Can you give me an example of what you’re trying to do?

      • Carlos Almeida

        I have a database with “name”, “lastname”, “id”, “color” that I embed to my project with this tutorial.

        Now I want to create a factory ( service ) with the data that I have in the database, so later I will call {{ human.name }} {{ human.lastname }} in the layout. Here you have an example of a simple service, but my data I should add from the database.

        Thanks in advice.

        /***********************************************************/
        angular.module(‘starter.services’, [])
        .factory(‘People’, function() {
        var people = [{
        id: 0,
        name: ‘Ben’,
        lastText: ‘Sparrow’,
        color: ‘blue’
        }, {
        id: 1,
        name: ‘Jack’,
        lastText: ‘Harrison’,
        color: ‘red’
        }];

        […..]

        /***********************************************************/

  • Guest

    I have a database with “name”, “lastname”, “id”, “color” that I embed to my project with this tutorial.

    Now I want to create a factory ( service ) with the data that I have in the database, so later I will call {{ human.name }} {{ human.lastname }} in the layout. Here you have an example of a simple service, but my data I should add from the database.

    Thanks in advice.

    /***********************************************************/
    angular.module(‘starter.services’, [])

    .factory(‘People’, function() {

    var people = [{

    id: 0,

    name: ‘Ben’,

    lastText: ‘Sparrow’,

    color: ‘blue’

    }, {

    id: 1,

    name: ‘Jack’,

    lastText: ‘Harrison’,

    color: ‘red’

    }];

    return {

    all: function() {

    return people;

    },

    remove: function(people) {

    peoples.splice(peoples.indexOf(chat), 1);

    },

    get: function(peopleId) {

    for (var i = 0; i < peoples.length; i++) {

    if (people[i].id === parseInt(peopleId)) {

    return peoples[i];

    }

    }

    return null;

    }

    }

    })

  • Emil Rasmussen

    Hi Nic.
    Really nice tutorial, again!

    I have searched a lot, and I haven’t found, what I was looking for.
    You have a button in this tutorial, which calls the function selectAll(), but what if you want to call the function automatically, when the page starts?

    Regards,

    • You would need to wrap it in an $ionicPlatform.ready() since the plugin is required to be loaded before use. You can do this directly in your controller.

      Let me know if that makes sense.

      Regards,

      • Emil Rasmussen

        Hi Nic,

        I have tried to take some of the code from the ionicController into the $ionicPlatform.ready(), but it seems like I can’t make it right.

        It should be said that I have included $scope as a parameter in ionicApp.run(….).

        Hope it makes sense to you.

        Regards,

        • You should not include $scope in your .run() method. You should be including $ionicPlatform.ready() in your Controller:

          You can include $ionicPlatform.ready() in any controller or method, and any code inside it will wait to execute until the app is ready (all plugins loaded).

          Regards,

          • Emil Rasmussen

            I don’t know why, but I simply can’t make it work.
            Would you mind looking at my app.js?
            https://github.com/fit-etar/religioner/blob/master/www/js/app.js

          • Your code seems fine. What do the Android logs say?

          • Emil Rasmussen

            I don’t know why, but there is a place, where it says:
            file:///android_asset/www/js/app.js: Line 32: Uncaught SyntaxError: Unexpected token {
            Do you have any idea, why it says that?

          • Emil Rasmussen

            You don’t have any idea, why this happens?

            Regards,

  • Enamul Haque

    Hello Dear,
    I am a new app developer. I try to access a local database created by sqlite3.exe. When i want to open the database it throws an execption type error in browser console
    .

    • You cannot test native plugins in your browser. You must test on a device or simulator.

      Regards,

  • Enamul Haque

    Hello Nic Raboy,
    You are nice man because you answer is swift. I have seen your tutorial. I have set all thing like your tutorial. It is the best one. I am using adobe phoneGap build for app. But i still struggling to connect sqlite database.I have my project in github. if you look at a glance, i will be grateful to you. My github Link https://github.com/enamul95/TestSqlite3.git
    Not: i have upload the project using command line to github and platforms/android/asset is now missing

    • I briefly read over your code and everything seems fine.

      I believe the problem is with the PhoneGap Build service. It is known to have issues when it comes to plugins, particularly when it involves manual placement of files. I strongly encourage you to do all your development and building locally and not use a cloud service.

      Regards,

  • Enamul Haque

    I am using windows. if i want to build android app locally what do i follow.

  • Dhruv Singhal

    Hi Nic, my application is crashing on loading the database, what could be the possible issue

    • What do the logs say? And what platform, Android or iOS?

      • Dhruv Singhal

        The database file wasn’t connectible, so I changed the DBHelper in the plugin(cordova plugin add https://github.com/an-rahulpandey/cordova-plugin-dbcopy.git) from www + database_file_name to database_file_name representing the database file location, it can find the database file now but cannot find the tables in it.

        Android it is, 5.0.

        • addictedboy

          Use the current version of the plugin

      • Dhruv Singhal

        02-04 16:17:34.612 4240-4332/? E/AndroidRuntime﹕ FATAL EXCEPTION: pool-1-thread-2
        Process: com.ionicframework.samplesqlite439715, PID: 4240
        java.lang.Error: Create Database Exception ============================ java.io.FileNotFoundException: www/myapplication.db
        at me.rahul.plugins.sqlDB.DatabaseHelper.createdatabase(DatabaseHelper.java:30)
        at me.rahul.plugins.sqlDB.sqlDB$1.run(sqlDB.java:88)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)

        This is the error I’m facing while using your implementation.

        • addictedboy

          Make sure your database file exists inside the www folder and is named myapplication.db. There has been recently change in the plugin so make sure you put the db file inside www folder not in assets directory.

      • Dhruv Singhal

        Thanks Nic, rahul pandey made some changes to the plugin, I used the one that is the latest one last committed feb 2nd, while you are using the one that is dated sept 11. Everything is working great, peace.

        • Just to confirm, the plugin changes that were made on 02/02/2015 are working fine when you place your database file in your project’s www directory?

          Thanks,

          • Dhruv Singhal

            Yes that’s working.
            Thanks Nic for all the help.

          • No problem, and thank you for your contributions 🙂

        • I tested the new version of the DBCopy plugin and updated this tutorial to reflect it. Thanks for reporting the change!

  • Enamul Haque

    Hi Nic Raboy,
    I am able to build ionic project in android But i want to build this project in windows phone . there is not much resource how to build windows phone apps. Please help me…..

    • Ionic Framework does not support Windows Phone. Only Android and iOS. Because of this, I won’t be able to help you.

      Sorry,

  • Hi Nic,

    Hoping you can help – I have had a similar implementation going since October(ish), I have jsut got around to deploying to IOS and keep getting the app rejected for the following reason – any suggestions of where to look? Backup storage is set to none so as far as I can tell there shouldn’t be an issue.

    I realise that this is specific, but I am willing ot bet that others will run into this issue.

    On launch and content download, your app stores 8.8 MB, which does not comply with the iOS Data Storage Guidelines.

    Thanks,

    John

    • It is a problem with the SQLite plugin as mentioned here:

      https://github.com/brodysoft/Cordova-SQLitePlugin/issues/143

      Developer seems to be aware of it and working on a fix.

      Regards,

      • Thanks, points me in the right direction.

        Nice write up by the way, wish I had time to do the same, I’ll keep plugging away though!

        Keep up the good work!

        • Thanks for the compliment!

          If you end up with a solution before the developer fixes the plugin, please report back. It will help everyone else who might suffer from the same problems.

          Regards,

          • Ok I have a working solution which I am just about to upload to Apple. This is taking some information from the above link, and from applying a bit of common sense.

            Step 1 : Find the file SQLitePlugin.m and go to line 170 ish. Now put the below lines:

            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
            NSString *libraryDirectory = [paths objectAtIndex:0];
            libraryDirectory = [libraryDirectory stringByAppendingString:@”/NoCloud”];
            NSError *err = nil;
            [self setAppDocsPath:libraryDirectory];

            In place of :

            NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
            NSLog(@”Detected docs path: %@”, docs);
            [self setAppDocsPath:docs];

            What this does is to tell the SQLitePlugin where to look for your database. The bit you are still missing is to get dbcopy to copy the .db file from the resources directory into the correct directory on the phone. To do this I did the following:

            Step 2: Find and open the plugin file sqlDB.m:

            Find the below:

            paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            documentsDirectory = [paths objectAtIndex:0];

            Replace with :

            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
            NSString *libraryDirectory = [paths objectAtIndex:0];
            libraryDirectory = [libraryDirectory stringByAppendingString:@”/NoCloud”];

            That’s it your app is back into a working state and now uses the Library/NoCloud directory rather than the Documents directory on the iphone.

            I’ll let you know if this solves the issues for Apples tests.

          • Thanks for reporting back!

          • I can confirm that this passes the Apple tests as my app is now available on the app store!

  • Enamul Haque

    How to use Tabs and sidemenu Project in icon?

  • Enamul Haque

    My Controller code is Below——-

    $scope.select = function() {

    var query = “SELECT * FROM branch_info”;
    $scope.results = [];
    $cordovaSQLite.execute(db, query).then(function(res) {
    if(res.rows.length > 0) {
    for(var i=0; i<res.rows.length; i++){

    //$scope.branch_code_values= res.rows.item(i).branch_code;
    $scope.results.push(res.rows.items(i));
    }

    } else {

    alert("No results found");
    }
    }, function (err) {
    // console.error(err);
    alert("Error Method");
    });
    }

    *****My sqlite database coluum

    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS branch_info (branch_code text, branch_name text,branch_address text, branch_phone text,branch_fax text)");

    I have already inserted from server end. I wan to display my information in a list like
    —————————————————————————–
    BranchCod:004
    Branch:Paltan
    address:paltan
    Ph:02222
    fax:00000
    ———————-
    BranchCod:005
    Branch:Motigilel
    address:Motigilel
    Ph:02222
    fax:00000

    what can i do in index.html in ionic to display abobe like?

    • I’m not going to look at code like this. Format it using pre and code tags, or put it on GitHub.

      Regards,

  • Enamul Haque

    My Controller code is Below——-

    $scope.select = function() {

    var query = “SELECT * FROM branch_info”;
    $scope.results = [];
    $cordovaSQLite.execute(db, query).then(function(res) {
    if(res.rows.length > 0) {
    for(var i=0; i<res.rows.length; i++){

    //$scope.branch_code_values= res.rows.item(i).branch_code;
    $scope.results.push(res.rows.items(i));
    }

    } else {

    alert("No results found");
    }
    }, function (err) {
    // console.error(err);
    alert("Error Method");
    });
    }

    My sqlite database column

    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS branch_info (branch_code text, branch_name text,branch_address text, branch_phone text,branch_fax text)");

    I have already inserted from server end. I wan to display my information in a list like
    —————————————————————————–
    BranchCod:004
    Branch:Paltan
    address:31/ 1 palton
    Ph:02222
    fax:00000
    ———————-
    BranchCod:005
    Branch:Motigilel
    address:31/ 1 Motigilel
    Ph:02222
    fax:00000

    what can i do in index.html in ionic to display abobe like?

  • Enamul Haque

    Hello Nic Raboy

    My git hub link: https://github.com/enamul95/TestSqlite.git
    I have already sink data from server. i want display data from sqlite in a list like

    BranchCod:004
    Branch:Paltan
    address:31/ 1 palton
    Ph:02222
    fax:00000
    ————————-
    BranchCod:005
    Branch:Motigilel
    address:31/ 1 Motigilel
    Ph:02222
    fax:00000
    ———————————
    More
    Please help me……….

    • I am not sure what you’re asking. I encourage you to post in the forums if you’re looking for help beyond what I’ve displayed in my tutorial. My tutorial is only intended to get you started, but the code you shared is a full project with other factors.

      • Enamul Haque

        Hello Nic Roboy.
        I have solved to retrieve value from sqlite to list.

  • Enamul Haque

    how to display value in a list from sqlite ?

  • Enamul Haque

    Hello
    Nic Raboy
    My Input field is below

    My default value (Enamul haque ) is not showing in the input field. it is showing when i remove ng-model=”changePassword.userid”.

    Please Help me how to show the default value in input field with ng-model?

  • Dhruv Singhal

    Hi Nic, I have another question we are able to launch our application on Android but the apple store is playing the constraint of iOS Data Storage Guidelines, where should be place the db file in IOS, my db size is 6.3 MB while the app is compiling to 12.91 MB

    • Please see this comment thread:

      https://www.thepolyglotdeveloper.com/2015/01/deploy-ionic-framework-app-pre-filled-sqlite-db/#comment-1839907610

      There is a bug in the SQLite plugin that the developer is aware of. The subscriber who made this comment was nice enough to share a possible temporary fix.

      Regards,

      • Dhruv Singhal

        Thanks Nic, I will try it out and reply you back.

        • Dhruv Singhal

          It’s not able to find the database.

          • Did you place the db file in your www directory?

          • Dhruv Singhal

            It’s 34mb in that case.

          • I’d be less concerned about the size and more concerned about the functionality to start. You can always make adjustments after you’ve gotten it working.

            Does it work?

            Regards,

          • Dhruv Singhal

            It’s giving error while accessing the db path, in the main function
            the destination path is null.

          • Put your full project on GitHub and I’ll check it out.

            Regards,

  • Maniya

    Hi, I got the following error “Uncaught TypeError: Cannot read property ‘sqlDB’ of undefined”. How to solve it?

    • Can you please share more information?:

      Are you testing in a device, simulator, or web browser?
      If you’re using a device or simulator are you using ionic serve or live-reload?
      What are the full logs? That error will have a line number associated to it with more information.

      Regards,

  • Jan Benda

    hey there, thanks for the tutorial!
    however im getting the same error as Maniya:
    TypeError: Cannot read property ‘sqlDB’ of undefined

    im not sure where to put the database.db for the “ionic serve” command, as im running my app in chrome

    • If you’re using ionic serve stop. This is a native device plugin and should never be tested in a web browser. Don’t even use live-reload as it could cause problems as well.

      Please include your full error log (from ADB) as well as your source code on GitHub. Then I’ll take a look.

      Regards,

      • Jan Benda

        hey nic, thanks for the response!
        i managed to get the db load to work on the iphone simulator.
        however now im forced to debug on the simulator, which seems like a nightmare to me.
        of course you have console.log working in xcode’s console, but no javascript error warnings, nor can you access an object properties through firebug..

        Do you know if there is a better workflow for that?

        • I know there are little things you can do here and there, but I personally don’t.

          The way I see it is you’re developing mobile applications not web applications. If you were developing native Android or iOS you’d have to use Xcode or ADB, so hybrid should be no different.

          Make sure you have your try / catch blocks in place and cross your fingers that you don’t have any massive code damage 😉

          • Jan Benda

            hey nic, thanks =)
            i think ill stick to localstorage + ngStorage for now

      • Karan Reddy

        Hi Nic, Thanks for sharing your ideas and support. Is there any hacky way to test this on browser, i am developing mobile applications. runing ionic run android slowing my development speed. Is there any suggested method to make it work on browser. If possible.

  • Venkatesh Angara

    Hi nic. I am having an error. I am running the app on a device. and the error is
    “File already exsists code 516”

    • The library can only copy the database one time. When I had written this tutorial, error codes were not working correctly, but it seems the developer probably fixed them as of now.

      When you get error code 516, you can probably over-look it.

      Regards,

  • DatzMe

    Should I install SQLite DB or just using cordova?

    • What does “just using cordova” mean?

      Regards,

      • DatzMe

        what I mean is that should i still install sqlLite before I use it?and what cordova do?Thank you for quick response..

        • You might want to do some research on what Apache Cordova is. Sounds like you might be confused on the goal of this article.

          SQLite is not something that has to be installed. We are also working with mobile applications and Apache Cordova is the framework.

          Regards,

          • DatzMe

            Yeah I’m a bit confuse.. I’m sorry I’m totally new with ionic framework and I want to learn how to connect this one to a database. I’m sorry if I’m confused… What should I study first to connect ionic to a database?

          • I strongly encourage you to first learn the basics of AngularJS and Apache Cordova before messing around with data storage. After this, you should figure out what kind of database you wish to use. A few of the popular ones are:

            Local Storage
            SQLite
            Firebase
            PouchDB
            Parse

            Start with the basics and work your way up.

            Regards,

          • DatzMe

            Thank you so much.. I will study it first

  • Frank Paap

    Everytime I try this app I get the error in weinre: “no such table: people (code 1): , while compiling: SELECT firstname, lastname FROM people”. I put the database in IonicProject/platforms/android/assets/,IonicProject/platforms/android/assets/www/ and IonicProject/www/

    I’m still getting the error. This is the database integration:

    if (window.sqlitePlugin) {

    Controller:

    $scope.selectAll = function() {

    What is going wrong? I’m testing on a tablet.

    Greetz Frank

    • Frank Paap

      Had to store the db in IonicProject/platforms/android/platform_www -.-

      • What version of the plugin are you using?

        The official plugin documentation says to put it in the www directory. I’m wondering if there is something wrong with your Apache Cordova installation. Files that were placed in the www, should be migrated to platform_www on build.

        Regards,

  • Tekeste Gebreanenia

    where do u get the console.log output?

  • Pl0xs

    When I try to add the code: window.plugins.sqlDB.copy(“populated.db”, function() {

    My texteditor says sqlDB is an unresolved variable. I’m sure I’ve added the cordova-plugin-dbcopy plugin

    • When you say text editor, that seems like a red flag to me.

      This plugin can only be tested from a device or simulator. It will not work in a web browser, or anything else.

      Please let me know what the device or simulator logs say and we can troubleshoot from there 🙂

      Regards,

      • Pl0xs

        I tried it on my iPhone, but when I try to view the app, it gives me a blank page. When I comment the specific code, it shows my original application.

        • Can you please put your code on GitHub and I’ll take a look? My assumption is something is missing or has a typo.

          Also, please paste your full logs.

          Regards,

          • Pl0xs

            https://github.com/Pl0xs/old

            I use the Ionic View app and “ionic serve”. Where do i see the logs?

          • I don’t recommend using “Ionic View” or “Ionic Serve”. They have a history of problems with native device plugins.

            You should compile the application and install it to your device. Then check out the logs because they’ll be more reliable. However, now I’m thinking your problem is because of “Ionic View” or “Ionic Serve”

            Regards,

  • Anand Dudheliya

    What happens when I update my app and the previous database needs to be updated? Will the previous database be deleted or I need to delete the database and then copy the new database to appropriate location?

  • faresallolo

    Hi
    Thank you for the awesome efforts. what if i wanted to use JDBC, remote database like dream factory ?

    • JDBC is Java. We are dealing with hybrid apps which don’t necessarily use Java. The only way you can access a remote database would be using a middleman web service.

      Regards,

  • bhavya

    hi nic,
    i am very new to angular js.
    i am trying send values using controllers but it is not working. can u please help me

    this is my index.html

    this is my app.js

    // Ionic Starter App

    // angular.module is a global place for creating, registering and retrieving Angular modules
    // ‘starter’ is the name of this angular module example (also set in a attribute in index.html)
    // the 2nd parameter is an array of ‘requires’

    angular.module(‘spicy’, [‘ionic’])

    .run(function($ionicPlatform) {
    $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) {
    StatusBar.styleDefault();
    }
    });
    });
    (function(angular) {
    ‘use strict’;
    var myApp = angular.module(‘spicy’, [‘ionic’]);

    myApp.controller(‘myController’, [‘$scope’, function($scope) {
    $scope.name= ‘hiee this is bhavya’;

    });
    })(window.angular);

    thnkq nic in advance and for the nice tutorial

    • Hi,

      I don’t look at code until I first see logs. If I can’t figure out your problem via the logs, your code will need to end up on GitHub. It is too complicated to read in the comments section which is why I won’t do it.

      Start with the logs and I’d be happy to help.

      Regards,

  • Enamul Haque

    Hello Nic Raboy
    When starting the application in portrait and changing the orientation
    to landscape, the tab bar disappears below the viewport. When starting the app in landscape and changing orientation to portrait, the tab bar is displayed half way up the page. It is occur in ipad. I built it adobe phonegap build. But at the same time In android tab is occurred such problem. In android it is fitted.

    Please help me……..

    • Sounds like this is unrelated to SQLite or my tutorial. You may want to post your question in the forums.

      Regards,

      • Enamul Haque

        ok. Thanks.

  • Anand Dudheliya

    Hey why not update the article the location of db has changed to www from asset and also “plugin add https://github.com/brodysoft/Cordova-SQLitePlugin.git” with “plugin add https://github.com/litehelpers/Cordova-sqlite-storage.git“. Also could you share a working apk file? I am having trouble copying the database

  • usman

    Hello Nic i have a problem in using sqlLite DB in Ionic Framework

    • What do the error logs say?

      • usman

        if u gave me Favour you Should check my Code i just want to Connect mysql DB in Ionic Framework i follow your Tuturiol but now i m stuck plz help me i want u to check my code plz tell me where i send u my code….

        • My tutorial is for SQLite, not MySQL. I encourage you to post in the forums if you wish to do MySQL.

          Regards,

  • ryan

    Hi Nick, How can I test on web browser, ionic serve.

  • Enamul Haque

    Hello Sir,
    I have used bellow code

    var insertqQuery = “INSERT INTO useridinfo (user_id) VALUES (?)”;

    In android it is working. But ios is not working anything goes wrong. Is IOS query is different from android.

    Please help me..

  • Nad

    Hi Nick,

    First of all, thanks a lot for this tutorial.

    I have tried to do exactly the same as you, but I keep getting this message in my log:

    “0 628839 error TypeError: null is not an object (evaluating ‘n.transaction’), http://10.18.196.186:8100/js/ng-cordova.min.js, Line: 9″

    And before that, I had this message in my console log

    1 107328 error There was an error copying the database: [object Object]
    2 107329 log OPEN database: populated.db
    3 107331 log DB opened: populated.db

    What would possibly be wrong? I have tried to comment the lines of the ConfigController but I still getting this message. Could you help

    • http://10.18.196.186:8100

      My assumption is you’re using ionic serve or live-reload. Don’t use either of those. They don’t work properly with native plugins.

      Regards,

      • Nad

        Thanks. I’ll give it a try.

  • Lardi

    Hi Nick.

    I do all the steps several times but I get this message in logcat

    I/chromium( 2456): [INFO:CONSOLE(20306)] “ReferenceError: db is not defined

    • Are you testing in a device or simulator? Are you using Ionic Serve, Ionic View, or Ionic Live-Reload? What platform are you testing on?

      The more information I have, the better I can help.

      Regards,

      • Lardi

        I used “genymotion” like you, and do testing for android same as you on a blank ionic project.
        Thanks

      • Lardi

        I am sorry after two days I figure that I forgot to write a second line in apps.js that define db var

        • So everything is good now?

          • Lardi

            Unfortunately, I get a lot of messages after this, I think most important of it.

            I/chromium( 4174): [INFO:CONSOLE(1075)] “processMessage failed: Error: ReferenceError: $cordovaSQLite is not defined”, source: file:///android_asset/www/cordova.js (1075)

            I/chromium( 4174): [INFO:CONSOLE(20306)] “TypeError: Cannot call method ‘transaction’ of null

          • Lardi

            I am sorry, everythings is Okay right now.
            Thanks Nic.

  • Enamul Haque

    Hello Nic Raboy.

    I have want to show value from sqlite to ionic list. I have used view

    //
    I have used controller below
    db.transaction(function(tx) {
    tx.executeSql(“SELECT * from branch_location;”, [], function(tx, res) {
    var len = res.rows.length;
    if(len>0){
    for (var i = 0; i < len; i++) {

    res.rows.item(i).slno, branch_code:
    res.rows.item(i).branch_code,branch_name:
    res.rows.item(i).branch_name});
    }

    Please help me..

  • Eduardo hillebrand

    Hello!! can u help me?

    my code:

    What Xcode returns:

    2015-05-14 22:51:05.203 Chef Airfryer[5530:60b] [sqlDB] Could not copy file from /var/mobile/Applications/61F258BF-2193-4B04-BF95-ADDC5FAAF9CD/Chef Airfryer.app/www/chefAirfyer.db to /var/mobile/Applications/61F258BF-2193-4B04-BF95-ADDC5FAAF9CD/Documents/chefAirfyer.db. Error = Error Domain=NSCocoaErrorDomain Code=260 “The operation couldn’t be completed. (Cocoa error 260.)” UserInfo=0x145097f0 {NSFilePath=/var/mobile/Applications/61F258BF-2193-4B04-BF95-ADDC5FAAF9CD/Chef Airfryer.app/www/chefAirfyer.db, NSUnderlyingError=0x14509790 “The operation couldn’t be completed. No such file or directory”}

    I’ve put the chefAirfyer.db on www folder.

    i don’t understand why this is happening, everithing appears be right.

    Thank you!

    • Eduardo hillebrand

      sorry, my bad.
      2 hours lost because an “r”.

  • Web Talk

    Hi Nic, thanks for showing path for ionic+ SQL Lite. I am facing issues after creating a db file named “mydb.sqbpro” using SQLITEBROWSER tool as mentioned above. DB file gets copied, but which running execute in controller – I get the following error : {“message”:”[26] DB[1] prepare() select distinct prod_cat_name from prod_catg [file is encrypted or is not a database]”,”code”:0}

    let me know if need to provide more details

    • Yea I’m not sure. Sounds like maybe your database is corrupt. Maybe try a different SQLite tool?

  • Lardi

    Hello Nic,
    Any way to use “query statement” in services instead of controllers to get variables there.
    sorry for my stupid question 🙂

    • Of course! You can make your own database service to streamline things. My example is only the most basic. I encourage you to get creative with things 🙂

  • anuj

    hi

    i did as that blog say’s now i am getting “Uncaught TypeError: Cannot read property ‘sqlDB’ of undefined”

    plesase help

    • Please paste your full logs into the comments.

      Regards,

  • bhavya

    hii nic
    here you used atom as editor …can pls demonstrate how to use atom on windows,i am unable get the log file for node.js

  • Can you prefill a database in SQLite with PouchDB? Any Example? (In the browser side too?) Thanks! 😀

  • Enamul Haque

    Hello Sir,
    Every time when i open app then it drop data. I just
    want to drop table when i want to add add column or new table created
    in updated version.
    I have used to your modified code. It is working nice.When i use bellow code It drops all data stored in locally
    db = window.sqlitePlugin.openDatabase({name: “DB”});

    })

    Please help me..

    • I’m sorry, but I don’t understand the issue. Can you please try again?

      Regards,

  • Fede Sardo

    Hi Nic,

    I followed your exameple but I am getting an isue inside the “$scope.selectAll” function.

    1) Based on my logs the database is successfully copied using window.plugins.sqlDB.copy

    2) But in the following piece of code:

    var query = “SELECT firstname, lastname FROM people”;

    $cordovaSQLite.execute(db, query, []).then(function(res) {…….}

    I am getting this issue:

    SQLitePlugin.executeSqlBatch: Error=[26] DB[1] prepare() SELECT firstname, lastname FROM people [file is encrypted or is not a database]

    My database script is:

    BEGIN TRANSACTION;

    CREATE TABLE people (id integer primary key, firstname text, lastname text);

    INSERT INTO people (id,firstname,lastname) VALUES (1,’Nic’,’Raboy’);

    INSERT INTO people (id,firstname,lastname) VALUES (2,’Maria ‘,’Campos’);

    INSERT INTO people (id,firstname,lastname) VALUES (3,’Max’,’Lynch’);

    INSERT INTO people (id,firstname,lastname) VALUES (4,’Ben’,’Sperry’);

    INSERT INTO people (id,firstname,lastname) VALUES (5,’Fede’,’Sardo’);

    COMMIT;

    Could you please help ? Thanks in advance.

    • Sounds like you might be trying to load the wrong database file. Can you copy and paste your ADB logs as well as put your project on GitHub?

      Regards,

  • Declan Murphy

    Hi Nic,

    I am using DB Browser for SQLite to create a “database.db” file but I keep getting an error message in logcat saying “file is encrypted or is not a database”

    To create the .db file I used the following method: File->Export->Database to SQL file. On the export configuration window I have all 3 options unselected (default). I then save the database as “database.db” and place it into “platforms/android/platform_www”. When I placed it in the normal www folder it did not located the database.

    Am I doing this the wrong way?

    • Declan Murphy

      Getting this now

      There was an error copying the database: OK:22
      I/Web Console(16167): OPEN database: iadb.db:174
      I/Web Console(16167): new transaction is waiting for open operation:105
      I/Web Console(16167): DB opened: iadb.db:79
      E/Web Console(16167): [object Object]:44
      E/Web Console(16167): [object Object]:44

  • Pradeep Godara

    Hi Nic,

    Amazing tutorial, i’ve tried a similar things but I am stuck, after all the analysis I could figure out that callback inside $ionicPlatform.ready(function() { //logic }); is not getting fired. Could you please guide what might be missing here…

    Thanks, Pradeep.

    • What do your logs say?

      • Pradeep Godara

        Hi Nic, please find the log on clicking select all button. Hope this helps!

        Running on Android SDK emulator.

        I/chromium( 1164): [INFO:CONSOLE(20306)] “TypeError: Cannot read property ‘transaction’ of null
        I/chromium( 1164): at Object.execute (file:///android_asset/www/js/ng-cordova.min.js:10:11962)
        I/chromium( 1164): at Scope.$scope.selectAll (file:///android_asset/www/js/app.js:25:24)
        I/chromium( 1164): at $parseFunctionCall (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:21044:18)
        I/chromium( 1164): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:53458:9
        I/chromium( 1164): at Scope.$eval (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:23100:28)
        I/chromium( 1164): at Scope.$apply (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:23199:23)
        I/chromium( 1164): at HTMLButtonElement. (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:53457:13)
        I/chromium( 1164): at HTMLButtonElement.eventHandler (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11713:21)
        I/chromium( 1164): at triggerMouseEvent (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2863:7)
        I/chromium( 1164): at tapClick (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2852:3)”, source: file:///android_asset/www/lib/ionic/js/ionic.bundle.js (20306)

        • I/chromium( 1164): [INFO:CONSOLE(20306)] “TypeError: Cannot read property ‘transaction’ of null
          I/chromium( 1164): at Scope.$scope.selectAll (file:///android_asset/www/js/app.js:25:24)

          Looks like your database isn’t being opened correctly. If you’ve placed debugging statements inside your $ionicPlatform.ready function and it is not printing out, then you may have found an issue that needs to be reported to the Ionic team. However, if the $ionicPlatform.ready is being hit and just the database code is not working, you may be suffering from a race condition.

          See this tutorial:

          https://www.thepolyglotdeveloper.com/2015/03/create-todo-list-mobile-app-using-ionic-framework/

          Notice in that tutorial I put all the database initialization inside a controller rather than the run function. Helps fix any race conditions.

          Regards,

          • Pradeep Godara

            Nic, I followed other tutorial and it worked, definitely was a race condition.

            But I am now facing another issue, very first time app launched fine, but if I kill app and comeback again it just shows me loading. To make it run again, I need to clear up the data from app settings or reinstall, any thoughts?

            Also for some reason ‘$stateParams’ are not passing id, categoryId and listId, any idea?

            Sorry I am bugging you with questions, pretty new to Cordova and Ionic.

          • What do your logs say? Every time you come to me with a problem, it is the first thing I’m going to ask you.

            Regards,

          • Pradeep Godara

            Hi Nic, Adding log for first app load till, I click back button and launch the app again, Hope you could find something.

            I did notice: [sqlite] DB[1]: will not dispose from a non-confining thread. Is that the issue?

            I/ActivityManager( 337): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.ionicframework.todoapp430323/.MainActivity (has extras)} from uid 10007 on display 0

            W/AudioTrack( 337): AUDIO_OUTPUT_FLAG_FAST denied by client

            V/WindowManager( 337): addAppToken: AppWindowToken{3f42955b token=Token{199a1c6a ActivityRecord{22f42a55 u0 com.ionicframework.todoapp430323/.MainActivity t66}}} to stack=1 task=66 at 0

            V/WindowManager( 337): Adding window Window{11c4c5a4 u0 Starting com.ionicframework.todoapp430323} at 2 of 5 (after Window{3075cb5f u0 com.android.launcher/com.android.launcher2.Launcher})

            I/Choreographer( 665): Skipped 106 frames! The application may be doing too much work on its main thread.

            I/art ( 1280): Not late-enabling -Xcheck:jni (already on)

            I/ActivityManager( 337): Start proc 1280:com.ionicframework.todoapp430323/u0a69 for activity com.ionicframework.todoapp430323/.MainActivity

            V/ActivityManager( 337): Display changed displayId=0

            I/Choreographer( 337): Skipped 48 frames! The application may be doing too much work on its main thread.

            I/Choreographer( 337): Skipped 30 frames! The application may be doing too much work on its main thread.

            I/ARMAssembler( 53): generated scanline__00000077:03010104_00008001_00000000 [ 89 ipp] (110 ins) at [0xb49fd680:0xb49fd838] in 10000000 ns

            I/WebViewFactory( 1280): Loading com.android.webview version 39 (1737576-arm) (code 300001)

            I/PackageManager( 337): Running dexopt on: /system/app/webview/webview.apk pkg=com.android.webview isa=arm vmSafeMode=false

            I/dex2oat ( 1296): /system/bin/dex2oat –zip-fd=6 –zip-location=/system/app/webview/webview.apk –oat-fd=7 –[email protected]@[email protected]@classes.dex –instruction-set=arm –instruction-set-features=default –runtime-arg -Xms64m –runtime-arg -Xmx512m –swap-fd=10

            I/dex2oat ( 1296): Decided to run without swap.

            W/dex2oat ( 1296): Verification of void com.android.org.chromium.content.browser.ContentViewCore.updateFrameInfo(float, float, float, float, float, float, float, float, float, float, float) took 115.347ms

            W/dex2oat ( 1296): Compilation of int com.android.org.chromium.media.VideoCaptureAndroid$BuggyDeviceHack.getImageFormat() took 187.763ms

            I/dex2oat ( 1296): dex2oat took 12.044s (threads: 1) arena alloc=37KB java alloc=1365KB native alloc=2MB free=1488KB

            I/art ( 1280): Background sticky concurrent mark sweep GC freed 1793(112KB) AllocSpace objects, 0(0B) LOS objects, 37% free, 377KB/605KB, paused 1.668ms total 109.330ms

            I/LibraryLoader( 1280): Time to load native libraries: 204 ms (timestamps 3709-3913)

            I/LibraryLoader( 1280): Expected native library version number “”,actual native library version number “”

            V/WebViewChromiumFactoryProvider( 1280): Binding Chromium to main looper Looper (main, tid 1) {2ba1e056}

            I/LibraryLoader( 1280): Expected native library version number “”,actual native library version number “”

            I/chromium( 1280): [INFO:library_loader_hooks.cc(104)] Chromium logging enabled: level = 0, default verbosity = 0

            W/art ( 1280): Suspending all threads took: 8.367ms

            I/art ( 1280): Background partial concurrent mark sweep GC freed 373(46KB) AllocSpace objects, 1(16KB) LOS objects, 54% free, 426KB/938KB, paused 13.995ms total 244.826ms

            I/BrowserStartupController( 1280): Initializing chromium process, singleProcess=true

            W/art ( 1280): Attempt to remove local handle scope entry from IRT, ignoring

            W/AudioManagerAndroid( 1280): Requires BLUETOOTH permission

            W/chromium( 1280): [WARNING:resource_bundle.cc(304)] locale_file_path.empty()

            I/chromium( 1280): [INFO:aw_browser_main_parts.cc(65)] Load from apk succesful, fd=30 off=46184 len=3037

            I/chromium( 1280): [INFO:aw_browser_main_parts.cc(78)] Loading webviewchromium.pak from, fd:31 off:229484 len:1089587

            E/chromium( 1280): [ERROR:gl_surface_egl.cc(165)] No suitable EGL configs found.

            E/chromium( 1280): [ERROR:gl_surface_android.cc(23)] GLSurfaceEGL::InitializeOneOff failed.

            E/chromium( 1280): [ERROR:browser_main_loop.cc(988)] GLSurface::InitializeOneOff failed

            W/chromium( 1280): [WARNING:data_reduction_proxy_settings.cc(331)] SPDY proxy OFF at startup

            W/art ( 1280): Attempt to remove local handle scope entry from IRT, ignoring

            W/AwContents( 1280): onDetachedFromWindow called when already detached. Ignoring

            D/SystemWebViewEngine( 1280): CordovaWebView is running on device made by: unknown

            W/art ( 1280): Attempt to remove local handle scope entry from IRT, ignoring

            W/art ( 1280): Attempt to remove local handle scope entry from IRT, ignoring

            I/art ( 1280): Background sticky concurrent mark sweep GC freed 1402(113KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 2MB/2MB, paused 1.884ms total 297.072ms

            V/WindowManager( 337): Adding window Window{1e08157d u0 com.ionicframework.todoapp430323/com.ionicframework.todoapp430323.MainActivity} at 2 of 6 (before Window{11c4c5a4 u0 Starting com.ionicframework.todoapp430323})

            I/art ( 1280): Background partial concurrent mark sweep GC freed 281(14KB) AllocSpace objects, 0(0B) LOS objects, 24% free, 2MB/3MB, paused 6.206ms total 351.181ms

            V/WindowManager( 337): Adding window Window{153418c3 u0 com.ionicframework.todoapp430323/com.ionicframework.todoapp430323.MainActivity} at 2 of 7 (before Window{1e08157d u0 com.ionicframework.todoapp430323/com.ionicframework.todoapp430323.MainActivity})

            I/Choreographer( 1280): Skipped 130 frames! The application may be doing too much work on its main thread.

            I/Choreographer( 1280): Skipped 92 frames! The application may be doing too much work on its main thread.

            D/gralloc_goldfish( 1280): Emulator without GPU emulation detected.

            I/ActivityManager( 337): Displayed com.ionicframework.todoapp430323/.MainActivity: +19s493ms

            I/Choreographer( 337): Skipped 36 frames! The application may be doing too much work on its main thread.

            I/MediaFocusControl( 337): AudioFocus abandonAudioFocus() from [email protected]kService[email protected]

            I/ActivityManager( 337): Killing 934:com.android.managedprovisioning/u0a8 (adj 15): empty #17

            I/Choreographer( 1280): Skipped 56 frames! The application may be doing too much work on its main thread.

            I/chromium( 1280): [INFO:CONSOLE(0)] “Refused to evaluate a string as JavaScript because ‘unsafe-eval’ is not an allowed source of script in the following Content Security Policy directive: “default-src ‘self’ data: gap: https://ssl.gstatic.com“. Note that ‘script-src’ was not explicitly set, so ‘default-src’ is used as a fallback.

            I/chromium( 1280): “, source: (0)

            D/JsMessageQueue( 1280): Set native->JS mode to OnlineEventsBridgeMode

            I/chromium( 1280): [INFO:CONSOLE(1188)] “deviceready has not fired after 5 seconds.”, source: file:///android_asset/www/cordova.js (1188)

            I/chromium( 1280): [INFO:CONSOLE(1181)] “Channel not fired: onPluginsReady”, source: file:///android_asset/www/cordova.js (1181)

            I/chromium( 1280): [INFO:CONSOLE(1181)] “Channel not fired: onCordovaReady”, source: file:///android_asset/www/cordova.js (1181)

            I/Choreographer( 1280): Skipped 34 frames! The application may be doing too much work on its main thread.

            W/PluginManager( 1280): THREAD WARNING: exec() call to CoreAndroid.show blocked the main thread for 27ms. Plugin should use CordovaInterface.getThreadPool().

            W/PluginManager( 1280): THREAD WARNING: exec() call to sqlDB.copy blocked the main thread for 18ms. Plugin should use CordovaInterface.getThreadPool().

            I/chromium( 1280): [INFO:CONSOLE(65)] “There was an error copying the database: OK”, source: file:///android_asset/www/js/app.js (65)

            V/SQLitePlugin( 1280): Android db implementation: sqlite4java (NDK)

            W/PluginManager( 1280): THREAD WARNING: exec() call to SQLitePlugin.open blocked the main thread for 35ms. Plugin should use CordovaInterface.getThreadPool().

            I/chromium( 1280): [INFO:CONSOLE(174)] “OPEN database: populated.db”, source: file:///android_asset/www/plugins/io.litehelpers.cordova.sqlite/www/SQLitePlugin.js (174)

            V/info ( 1280): Open sqlite db: /data/data/com.ionicframework.todoapp430323/databases/populated.db

            I/sqlite4java( 1280): [sqlite] DB[1]: instantiated [/data/data/com.ionicframework.todoapp430323/databases/populated.db]

            E/art ( 1280): No implementation found for java.lang.String com.almworks.sqlite4java._SQLiteSwiggedJNI.sqlite3_libversion() (tried Java_com_almworks_sqlite4java__1SQLiteSwiggedJNI_sqlite3_1libversion and Java_com_almworks_sqlite4java__1SQLiteSwiggedJNI_sqlite3_1libversion__)

            I/art ( 1280): Background sticky concurrent mark sweep GC freed 8041(417KB) AllocSpace objects, 0(0B) LOS objects, 14% free, 2MB/3MB, paused 3.264ms total 287.593ms

            I/sqlite4java( 1280): [sqlite] Internal: loaded sqlite4java-android-armv7l from system path

            I/sqlite4java( 1280): [sqlite] Internal: loaded sqlite 3.8.7, wrapper 1.3

            I/sqlite4java( 1280): [sqlite] DB[1]: opened

            I/chromium( 1280): [INFO:CONSOLE(105)] “new transaction is waiting for open operation”, source: file:///android_asset/www/plugins/io.litehelpers.cordova.sqlite/www/SQLitePlugin.js (105)

            I/chromium( 1280): [INFO:CONSOLE(79)] “DB opened: populated.db”, source: file:///android_asset/www/plugins/io.litehelpers.cordova.sqlite/www/SQLitePlugin.js (79)

            I/chromium( 1280): [INFO:CONSOLE(101)] “{“ID”:1,”category_name”:”Shopping”}”, source: file:///android_asset/www/js/app.js (101)

            I/chromium( 1280): [INFO:CONSOLE(101)] “{“ID”:2,”category_name”:”Chores”}”, source: file:///android_asset/www/js/app.js (101)

            I/chromium( 1280): [INFO:CONSOLE(101)] “{“ID”:3,”category_name”:”Office”}”, source: file:///android_asset/www/js/app.js (101)

            W/PluginManager( 1280): THREAD WARNING: exec() call to SQLitePlugin.backgroundExecuteSqlBatch blocked the main thread for 73ms. Plugin should use CordovaInterface.getThreadPool().

            D/gralloc ( 53): Registering a buffer in the process that created it. This may cause memory ordering problems.

            E/libEGL ( 53): called unimplemented OpenGL ES API

            E/SurfaceFlinger( 53): glCheckFramebufferStatusOES error 0

            E/SurfaceFlinger( 53): got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot

            W/WindowManager( 337): Screenshot failure taking screenshot for (480×800) to layer 21005

            W/PluginManager( 1280): THREAD WARNING: exec() call to CoreAndroid.exitApp blocked the main thread for 177ms. Plugin should use CordovaInterface.getThreadPool().

            W/ResourceType( 759): No package identifier when getting value for resource number 0x00000000

            W/PackageManager( 759): Failure retrieving resources for com.ionicframework.todoapp430323: Resource ID #0x0

            I/Choreographer( 665): Skipped 212 frames! The application may be doing too much work on its main thread.

            W/IInputConnectionWrapper( 1280): showStatusIcon on inactive InputConnection

            I/Choreographer( 665): Skipped 158 frames! The application may be doing too much work on its main thread.

            I/Choreographer( 337): Skipped 56 frames! The application may be doing too much work on its main thread.

            I/ActivityManager( 337): Killing 915:com.android.printspooler/u0a39 (adj 15): empty #17

            I/Choreographer( 337): Skipped 36 frames! The application may be doing too much work on its main thread.

            W/sqlite4java( 1280): [sqlite] DB[1]: will not dispose from a non-confining thread

            I/Choreographer( 1280): Skipped 30 frames! The application may be doing too much work on its main thread.

            W/AudioTrack( 337): AUDIO_OUTPUT_FLAG_FAST denied by client

            I/ActivityManager( 337): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.ionicframework.todoapp430323/.MainActivity (has extras)} from uid 10007 on display 0

            V/WindowManager( 337): addAppToken: AppWindowToken{2a53d622 token=Token{3fae57ed ActivityRecord{73be604 u0 com.ionicframework.todoapp430323/.MainActivity t67}}} to stack=1 task=67 at 0

            I/Choreographer( 665): Skipped 70 frames! The application may be doing too much work on its main thread.

            V/WindowManager( 337): Adding window Window{24935e70 u0 Starting com.ionicframework.todoapp430323} at 2 of 5 (after Window{3075cb5f u0 com.android.launcher/com.android.launcher2.Launcher})

            W/ActivityManager( 337): Activity pause timeout for ActivityRecord{3020278f u0 com.android.launcher/com.android.launcher2.Launcher t65}

            I/Choreographer( 337): Skipped 48 frames! The application may be doing too much work on its main thread.

            W/art ( 1280): Attempt to remove local handle scope entry from IRT, ignoring

            W/AwContents( 1280): onDetachedFromWindow called when already detached. Ignoring

            I/Choreographer( 337): Skipped 47 frames! The application may be doing too much work on its main thread.

            D/SystemWebViewEngine( 1280): CordovaWebView is running on device made by: unknown

            W/art ( 1280): Attempt to remove local handle scope entry from IRT, ignoring

            W/art ( 1280): Attempt to remove local handle scope entry from IRT, ignoring

            V/WindowManager( 337): Adding window Window{2bc797a5 u0 com.ionicframework.todoapp430323/com.ionicframework.todoapp430323.MainActivity} at 2 of 6 (before Window{24935e70 u0 Starting com.ionicframework.todoapp430323})

            V/WindowManager( 337): Adding window Window{1a5c8b2b u0 com.ionicframework.todoapp430323/com.ionicframework.todoapp430323.MainActivity} at 2 of 7 (before Window{2bc797a5 u0 com.ionicframework.todoapp430323/com.ionicframework.todoapp430323.MainActivity})

            I/Choreographer( 1280): Skipped 44 frames! The application may be doing too much work on its main thread.

            I/Choreographer( 1280): Skipped 33 frames! The application may be doing too much work on its main thread.

            D/TaskPersister( 337): removeObsoleteFile: deleting file=66_task.xml

            I/ActivityManager( 337): Displayed com.ionicframework.todoapp430323/.MainActivity: +2s49ms

            I/Choreographer( 337): Skipped 35 frames! The application may be doing too much work on its main thread.

            I/chromium( 1280): [INFO:CONSOLE(0)] “Refused to evaluate a string as JavaScript because ‘unsafe-eval’ is not an allowed source of script in the following Content Security Policy directive: “default-src ‘self’ data: gap: https://ssl.gstatic.com“. Note that ‘script-src’ was not explicitly set, so ‘default-src’ is used as a fallback.

            I/chromium( 1280): “, source: (0)

            D/JsMessageQueue( 1280): Set native->JS mode to OnlineEventsBridgeMode

            I/chromium( 1280): [INFO:CONSOLE(1188)] “deviceready has not fired after 5 seconds.”, source: file:///android_asset/www/cordova.js (1188)

            I/chromium( 1280): [INFO:CONSOLE(1181)] “Channel not fired: onPluginsReady”, source: file:///android_asset/www/cordova.js (1181)

            I/chromium( 1280): [INFO:CONSOLE(1181)] “Channel not fired: onCordovaReady”, source: file:///android_asset/www/cordova.js (1181)

            W/PluginManager( 1280): THREAD WARNING: exec() call to sqlDB.copy blocked the main thread for 38ms. Plugin should use CordovaInterface.getThreadPool().

            I/art ( 1280): Background sticky concurrent mark sweep GC freed 7018(259KB) AllocSpace objects, 0(0B) LOS objects, 12% free, 2MB/3MB, paused 2.359ms total 127.362ms

            I/art ( 650): Background sticky concurrent mark sweep GC freed 4572(224KB) AllocSpace objects, 0(0B) LOS objects, 17% free, 1660KB/2008KB, paused 5.437ms total 133.307ms

            I/UsageStatsService( 337): User[0] Flushing usage stats to disk

            I/art ( 337): Background sticky concurrent mark sweep GC freed 16463(1244KB) AllocSpace objects, 4(64KB) LOS objects, 17% free, 6MB/8MB, paused 4.492ms total 100.756ms

          • I think this is the chunk you want to look at:

            Looks like you’re getting a Java exception. Java exceptions need to be reported to the plugin developer because they are out of my control.

            Regards,

  • Hi Nic, ¿what do you think about using service pattern? 😀 This is my example: https://gist.github.com/jdnichollsc/9ac79aaa3407e92677ba

  • shahril

    hi Nic, I already read your tutorial . But, how to connect Mysql database with sqlite ? Now I’m working on ionic framework too and just want to retrieve the data to the end user. The data come from mysql database and I want to store the data into local storage. So when the user dont have the internet, they still can view the data . Can you help me ?

  • Nicolas

    hi Nic, thanks for your detailed tutorial, i’m having bad times connecting my database, i added this line : db = $cordovaSQLite.openDB(“Expertise.db”); before the execute function in my controller, otherwise i don’t have any log.

    Here is what i got in my log:
    … Good news: SQLite is thread safe!
    new transaction is waiting for open operation
    DB opened: Database.db
    SELECTED -> undefined undefined

    Thanks for your time, regards, (tell me if you need more log)

    • Please open an issue ticket with the plugin developer for SQLite. The latest BrodySoft plugin has a bunch of problems and I haven’t yet had a chance to open a ticket.

      new transaction is waiting for open operation

      That line is the line I get too.

      Regards,

      • Nicolas

        Hi thanks for your answer, after some research, i’ve managed to fix the issue just by replacing the db = $cordovaSQLite.openDB(“Database.db”) line by db = window.sqlitePlugin.openDatabase({name: “Database.db”, location: 1});

        However, now i have another error : ERROR: {“code”:5,”message”:”no such table: Installateur”}.

        I populated my database using this : http://www.tutorialspoint.com/sqlite/sqlite_create_database.htm
        Otherwise I could not have a .db file like you even with Db Browser for SQLite (we can only export in .SQL). I opened my Database.db with Db Browser after creating it to check, and there is the Installateur table. I tried using a .SQL and i get the exact same error.

        What should I do ? thank you for your time

  • Jomel Barbadillo

    Thank You Nic! I’ve been watching tutorial for almost a month, but damn your tutorial helps me a lot. God bless you bro!

  • RedhopIT

    That’s great Nic.

    I found out another solution:

    The $cordovaSQLite plugin has an issue, it doesn’t support createFromLocation attribute that allows you to use an existing sqlite database from www folder.

    I debugged the plugin and figured out that instead o $cordovaSQLite.openDB, we might use window.sqlitePlugin.opendatabase with createFromLocation plugin,

    I described the solution here: http://redwanhilali.com/ionic-sqlite/

    I hope this helps someone

  • shahril

    hi Nic .
    I already folllowed your tutorial. But, I got the problem when running at Android SDK emulator. The error is “[ERROR] Error initializing Cordova: Class Not Found. So, how to fix this error ?

    • Please paste the full ADB logs.

      Regards,

      • shahril

        I/Choreographer( 599): Skipped 30 frames! The application may be doing too much work on its main thread.

        I/art ( 599): Background partial concurrent mark sweep GC freed 185(8KB) AllocSpace objects, 4(178KB) LOS objects, 16% free, 20MB/24MB, paused 1.713ms total 181.886ms

        I/ActivityManager( 334): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.phonegap.www/.Shahrilionic (has extras)} from uid 10007 on display 0

        V/WindowManager( 334): addAppToken: AppWindowToken{1636bd token=Token{2e0fbe14 ActivityRecord{109e0067 u0 com.phonegap.www/.Shahrilionic t27}}} to stack=1 task=27 at 0

        V/WindowManager( 334): Adding window Window{134a780 u0 Starting com.phonegap.www} at 3 of 8 (after Window{313e45f9 u0 com.android.launcher/com.android.launcher2.Launcher})

        W/AudioTrack( 334): AUDIO_OUTPUT_FLAG_FAST denied by client

        I/ActivityManager( 334): Start proc 1424:com.phonegap.www/u0a57 for activity com.phonegap.www/.Shahrilionic

        I/art ( 1424): Not late-enabling -Xcheck:jni (already on)

        V/PhoneStatusBar( 781): setLightsOn(true)

        I/CordovaLog( 1424): Changing log level to DEBUG(3)

        D/CordovaActivity( 1424): CordovaActivity.init()

        I/WebViewFactory( 1424): Loading com.android.webview version 39 (1737576-arm) (code 300001)

        I/LibraryLoader( 1424): Time to load native libraries: 17 ms (timestamps 4489-4506)

        I/LibraryLoader( 1424): Expected native library version number “”,actual native library version number “”

        V/WebViewChromiumFactoryProvider( 1424): Binding Chromium to main looper Looper (main, tid 1) {9a8cef7}

        I/LibraryLoader( 1424): Expected native library version number “”,actual native library version number “”

        I/chromium( 1424): [INFO:library_loader_hooks.cc(104)] Chromium logging enabled: level = 0, default verbosity = 0

        I/BrowserStartupController( 1424): Initializing chromium process, singleProcess=true

        W/art ( 1424): Attempt to remove local handle scope entry from IRT, ignoring

        W/AudioManagerAndroid( 1424): Requires BLUETOOTH permission

        W/chromium( 1424): [WARNING:resource_bundle.cc(304)] locale_file_path.empty()

        I/chromium( 1424): [INFO:aw_browser_main_parts.cc(65)] Load from apk succesful, fd=30 off=46184 len=3037

        I/chromium( 1424): [INFO:aw_browser_main_parts.cc(78)] Loading webviewchromium.pak from, fd:31 off:229484 len:1089587

        E/chromium( 1424): [ERROR:gl_surface_egl.cc(165)] No suitable EGL configs found.

        E/chromium( 1424): [ERROR:gl_surface_android.cc(23)] GLSurfaceEGL::InitializeOneOff failed.

        E/chromium( 1424): [ERROR:browser_main_loop.cc(988)] GLSurface::InitializeOneOff failed

        W/chromium( 1424): [WARNING:data_reduction_proxy_settings.cc(331)] SPDY proxy OFF at startup

        W/art ( 1424): Attempt to remove local handle scope entry from IRT, ignoring

        W/AwContents( 1424): onDetachedFromWindow called when already detached. Ignoring

        D/CordovaActivity( 1424): CordovaActivity.createViews()

        D/PluginManager( 1424): init()

        D/CordovaWebView( 1424): CordovaWebView is running on device made by: unknown

        W/art ( 1424): Attempt to remove local handle scope entry from IRT, ignoring

        D/CordovaWebView( 1424): >>> loadUrl(file:///android_asset/www/index.html)

        D/CordovaWebView( 1424): >>> loadUrlNow()

        I/art ( 1424): Background sticky concurrent mark sweep GC freed 3436(253KB) AllocSpace objects, 2(32KB) LOS objects, 28% free, 803KB/1117KB, paused 1.163ms total 268.513ms

        D/CordovaActivity( 1424): Resuming the App

        V/WindowManager( 334): Adding window Window{365c4b29 u0 com.phonegap.www/com.phonegap.www.Shahrilionic} at 3 of 9 (before Window{134a780 u0 Starting com.phonegap.www})

        D/SoftKeyboardDetect( 1424): Ignore this event

        D/gralloc_goldfish( 1424): Emulator without GPU emulation detected.

        I/ActivityManager( 334): Displayed com.phonegap.www/.Shahrilionic: +3s98ms

        D/SoftKeyboardDetect( 1424): Ignore this event

        D/CordovaWebViewClient( 1424): onPageStarted(file:///android_asset/www/index.html)

        D/CordovaActivity( 1424): onMessage(onPageStarted,file:///android_asset/www/index.html)

        D/JsMessageQueue( 1424): Set native->JS mode to OnlineEventsBridgeMode

        I/art ( 1424): Background partial concurrent mark sweep GC freed 4107(237KB) AllocSpace objects, 1(16KB) LOS objects, 52% free, 910KB/1934KB, paused 972us total 193.503ms

        D/CordovaLog( 1424): file:///android_asset/www/plugins/cordova-plugin-console/www/console-via-logger.js: Line 173 : No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.

        I/chromium( 1424): [INFO:CONSOLE(173)] “No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.”, source: file:///android_asset/www/plugins/cordova-plugin-console/www/console-via-logger.js (173)

        D/CordovaActivity( 1424): onMessage(spinner,stop)

        D/PluginManager( 1424): exec() call to unknown plugin: Device

        V/WindowManager( 334): not Base app: Adding window Window{277be586 u0 com.phonegap.www/com.phonegap.www.Shahrilionic} at 4 of 9

        E/CordovaWebView( 1424): CordovaWebView: TIMEOUT ERROR!

        • The only thing that stands out is as follows:

          D/CordovaLog( 1424): file:///android_asset/www/plugins/cordova-plugin-console/www/console-via-logger.js: Line 173 : No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.

          You might see this:

          https://www.thepolyglotdeveloper.com/2015/05/whitelist-external-resources-for-use-in-ionic-framework/

          Regards,

          • jignesh

            Hey Nic Raboy,

            Your above comment save me. I was getting above error whcich you have mentioned and struggling with that from the long time. I want to say thanks to you for this comment. It saves my lot of time. Your effort and work is commendable.

          • No problem! Thanks for the compliments 🙂

  • sidney

    Hi Nic thanks for the tutorials but however i’m getting this error ” TypeError: Cannot call method ‘transaction’ of null” in the debug logs.I have tried every solution mentioned in the thread by some guys who got the same error but none of them is helping .can you kindly assist

    • It is a known bug with the plugin. I suggest you add your comments to the issue tracker of the plugin on GitHub.

      Regards,

  • hrshadhin

    Hi, I face some problem with this tutorial. Please help me.
    when i run app for first time its fine. bt 2nd time its not work! where is the problem i can’t find. I build app for android.
    Thanks.

    • What do your logs say?

      • NIsham Mahsin

        i am also getting the same problem.
        it works for first time bt 2nd time its not work.
        this is the log
        08-04 13:31:02.390: I/chromium(1830): at Object.switcher.transition (file:///android_asset/www/lib/ionic-angular.js:4583:22)

        08-04 13:31:02.390: I/chromium(1830): at file:///android_asset/www/lib/ionic-angular.js:6209:16
        08-04 13:31:02.390: I/chromium(1830): at file:///android_asset/www/lib/ionic-angular.js:4461:25

        08-04 13:31:02.390: I/chromium(1830): at Object.switcher.render (file:///android_asset/www/lib/ionic-angular.js:4550:23)”, source: file:///android_asset/www/lib/angular.js (11607)

        08-04 13:31:37.870: I/chromium(1830): [INFO:CONSOLE(11607)] “TypeError: Cannot call method ‘transaction’ of null

        • Would you mind putting your full project on GitHub?

  • NIsham Mahsin

    Thanks for this tutorial..
    i am getting error

    TypeError: window.plugins is undefined

    window.plugins.sqlDB.copy(“populated.db”, function() {

  • NIsham Mahsin

    what doest it means ?’ ‘UPDATE 02/02/2015: To include the database file into your project, it must live in your project’s www directory.’

    where i have to include my database file,?

    in platforms/android/assets or in www/ folder?

    • In your www/ directory. That is what the documentation for the plugin calls for.

  • Fajar Alif

    Hi, Nic thanks for the ionic tutorial..

    I’m getting error while run the app for the 2nd time

    The logs says :
    I/chromium( 3183): [INFO:CONSOLE(20434)] “TypeError: Cannot read property ‘transaction’ of null

    What should I do ?

    • Full error logs please.

      • Fajar Alif

        I/chromium( 2216): [INFO:CONSOLE(20434)] “TypeError: Cannot read property ‘transaction’ of null

        I/chromium( 2216): at Object.execute (file:///android_asset/www/js/ng-cordova.min.js:9:7454)

        I/chromium( 2216): at Scope.$scope.selectData (file:///android_asset/www/js/app.js:31:26)

        I/chromium( 2216): at $parseFunctionCall (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:21172:18)

        I/chromium( 2216): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:53674:9

        I/chromium( 2216): at Scope.$eval (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:23228:28)

        I/chromium( 2216): at Scope.$apply (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:23327:23)

        I/chromium( 2216): at HTMLButtonElement. (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:53673:13)

        I/chromium( 2216): at HTMLButtonElement.eventHandler (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:11841:21)

        I/chromium( 2216): at triggerMouseEvent (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2865:7)

        I/chromium( 2216): at tapClick (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2854:3)”, source: file:///android_asset/www/lib/ionic/js/ionic.bundle.js (20434)

        • Can you put your full project on GitHub? I’ll take a look if you do that.

          Regards,

  • Piush Gupta

    Hi Nic,

    I’m getting error while running the app in chrome.

    Uncaught TypeError: Cannot read property ‘sqlDB’ of undefined(anonymous function) @ app.js:19
    (anonymous function) @ ionic.bundle.js:44991
    onPlatformReady @ ionic.bundle.js:2447
    onWindowLoad @ ionic.bundle.js:2428

    what should i do to run it in chrome?

    • Read this and if you still have questions, comment back:

      https://www.thepolyglotdeveloper.com/2015/02/properly-testing-ionic-framework-mobile-application/

      Regards,

      • Piush Gupta

        got it thanks .

        I have a .db and getting a blob as response after running the query and the blob contains a zip file how to get the data of that file ?

        • You’ll have to find some zip library to be able to process the binary data that exists in that particular column.

          Regards,

          • sylfree9999

            Hi Nic,
            Thanks for your great tutorials.
            I have bumped into the same issue as Piush. But I think the SQLite plugin can not be tested during browser. So I tried adb logcat, the error seems to be the same as below. I’m sure I installed Cordova SQLite and dbCopy, why this still shows? can you help?

            I/ActivityManager( 554): Displayed com.ionicframework.yooyacrm181448/.MainActivity: +819ms

            D/JsMessageQueue(12491): Set native->JS mode to OnlineEventsBridgeMode

            I/chromium(12491): [INFO:CONSOLE(21157)] “TypeError: Cannot read property ‘sqlDB’ of undefined

            I/chromium(12491): at new (file:///android_asset/www/js/app.js:120:23)

            I/chromium(12491): at invoke (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:13277:17)

            I/chromium(12491): at Object.instantiate (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:13285:27)

            I/chromium(12491): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:17841:28

            I/chromium(12491): at self.appendViewElement (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:52255:24)

            I/chromium(12491): at Object.switcher.render (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:50449:41)

            I/chromium(12491): at Object.switcher.init (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:50369:20)

            I/chromium(12491): at self.render (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:52115:14)

            I/chromium(12491): at self.register (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:52073:10)

            I/chromium(12491): at updateView (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:57485:23)”, source: file:///android_asset/www/lib/ionic/js/ionic.bundle.js (21157)

            I/chromium(12491): [INFO:CONSOLE(173)] “No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.”, source: file:///android_asset/www/plugins/cordova-plugin-console/www/console-via-logger.js (173)

            D/PluginManager(12491): exec() call to unknown plugin: Console

          • You might be suffering from a race condition. Try initializing your database in a controller rather than the .run() function. Since the .run() function is asynchronous, it might be finishing before the database is copied / working.

  • Krzysztof Nawrocki

    Nice tutorial Nic.

    Is it possible to download database file from server when app starts ?

    Thanks.

    • To my knowledge you’d have to import data rather than download a sqlite file. In Android (not sure about iOS), the database file is kept in a protected partition, not the publicly accessible sdcard partition. Downloading a sqlite file would add the file to the sdcard partition.

      Regards,

  • Sonu Kapoor

    Hi Nic,

    Nice article. Two questions:

    Without using the copy plugin: I tried to upload the db file into my www folder under ProjectName/platforms/ios/www and when I run the app, I get the following error: ERROR: {“code”:5,”message”:”no such table: Products”}. I have also tried to copy the db file into the ProjectName/www and it has the same effect.
    Do we need to use the copy plugin?

    • At the time of writing this article, the only way to use a pre-filled sqlite database was to use the copy plugin. Whether that is still true, I don’t know. Are you sure that your sqlite file is correct and not corrupt? Can you confirm that you are not using ionic serve, ionic live-reload, ionic view, or phonegap build? None of those will work properly with these plugins.

      Regards,

      • Sonu Kapoor

        I got the copy plugin working and like you said it really seems to be the only to use a pre-filled DB. I wish your blog post could be added to the git documentation of the plugin. I am sure a ton of people would appreciate it. Thanks for sharing and the prompt response.

  • AP

    Hi Nic,
    I’ve followed the tutorial fairly closely. However, I don’t seem to local the db that I am expecting to get created in the IOS Simulator.

    I can see a lot of other .sqlite & .db files under ~/Library/…./CoreSimulator/…. but not the one I am expecting. The application itself seems to behave well but the DB operations don’t seem to write to any database nor it causes the application to fail.

    Any hints would be helpful.

    • Are you using Xcode 7 with iOS 9? If so there are currently issues with Apache Cordova / Ionic Framework the latest release.

      If the above doesn’t apply, do you happen to have any log output?

      Regards,

      • AP

        Xcode 6.4 on IOS 10.10.5.
        Investigation show a potential problem with the way I’m trying to enter the method. I pass in couple of other objects to this function.

        run(function($ionicPlatform, $cordovaSQLite, Config)

        Do I have access to my Config object from this location? Or is it too early?

        • What is Config? A service, factory, other? What does it do?

          What do your logs say? I cannot help any further without seeing logs.

          Regards,

          • AP

            Fair enough. Config is a factory and stores a application properties. I’m happy to ignore Config for now to keep things simple.

            ‘$cordovaSQLite’ passed in to the run function appears to be an issue in my case – which I’ve by verified by placing a console.log statement as the first line of the $ionicPlatform.ready function – which get printed only when I take out $cordovaSQLite from the following statement

            .run(function($ionicPlatform, $cordovaSQLite).

            — Simulator log —
            Sep 22 19:18:56 username installd[19309]: 0x10d21b000 -[MIClientConnection _doBackgroundInstallationForPath:withOptions:completion:]: Install of “/Users/username/workspace/appName/appName/platforms/ios/build/emulator/AppName.app” type Developer requested by CoreSimulatorBridge (pid 19322)
            state->old_bundle: /Users/username/Library/Developer/CoreSimulator/Devices/84839033-D772-4623-86AC-0F6599E4BB74/data/Containers/Bundle/Application/B8838BE8-66FE-428A-B9EB-AD195550ABAC/AppName.app
            state->new_bundle: /Users/username/workspace/appName/appName/platforms/ios/build/emulator/AppName.app
            state->dst_bundle: /Users/username/Library/Developer/CoreSimulator/Devices/84839033-D772-4623-86AC-0F6599E4BB74/data/Library/Caches/com.apple.mobile.installd.staging/temp.CcK4vd/extracted/Payload//AppName.app, binaryDiff flag: FALSE
            Sep 22 19:19:43 username AppName[19366]: assertion failed: 14F27 12H141: libxpc.dylib + 69007 [55209BF0-C183-332C-B272-05E5362CC077]: 0x7d
            Sep 22 19:19:43 username.local AppName[19366]: DiskCookieStorage changing policy from 2 to 0, cookie file: file:///Users/username/Library/Developer/CoreSimulator/Devices/84839033-D772-4623-86AC-0F6599E4BB74/data/Containers/Data/Application/296DD24E-E299-43EA-8CEE-B8A652933B72/Library/Cookies/Cookies.binarycookies
            Sep 22 19:19:43 username.local AppName[19366]: Apache Cordova native platform version 3.8.0 is starting.
            Sep 22 19:19:43 username.local AppName[19366]: Multi-tasking -> Device: YES, App: YES
            Sep 22 19:19:43 username.local AppName[19366]: Unlimited access to network resources
            Sep 22 19:19:43 username.local AppName[19366]:
            Sep 22 19:19:45 username.local AppName[19366]: [CDVTimer][splashscreen] 567.866981ms
            Sep 22 19:19:45 username.local AppName[19366]: [CDVTimer][keyboard] 0.064015ms
            Sep 22 19:19:45 username.local AppName[19366]: [CDVTimer][TotalPluginStartup] 568.277001ms
            Sep 22 19:19:46 username.local AppName[19366]: Resetting plugins due to page load.
            Sep 22 19:19:46 username.local AppName[19366]: Finished load of: file:///Users/username/Library/Developer/CoreSimulator/Devices/84839033-D772-4623-86AC-0F6599E4BB74/data/Containers/Bundle/Application/BFDB7EF6-D36E-4D10-A981-042D70FAD821/AppName.app/www/index.html#/home
            Sep 22 19:55:26 username installd[20348]: 0x116a05000 -[MIClientConnection _doBackgroundInstallationForPath:withOptions:completion:]: Install of “/Users/username/workspace/appName/appName/platforms/ios/build/emulator/AppName.app” type Developer requested by CoreSimulatorBridge (pid 20361)
            state->old_bundle: /Users/username/Library/Developer/CoreSimulator/Devices/84839033-D772-4623-86AC-0F6599E4BB74/data/Containers/Bundle/Application/BFDB7EF6-D36E-4D10-A981-042D70FAD821/AppName.app
            state->new_bundle: /Users/username/workspace/appName/appName/platforms/ios/build/emulator/AppName.app
            state->dst_bundle: /Users/username/Library/Developer/CoreSimulator/Devices/84839033-D772-4623-86AC-0F6599E4BB74/data/Library/Caches/com.apple.mobile.installd.staging/temp.qvpeGg/extracted/Payload//AppName.app, binaryDiff flag: FALSE
            Sep 22 19:56:11 username AppName[20406]: assertion failed: 14F27 12H141: libxpc.dylib + 69007 [55209BF0-C183-332C-B272-05E5362CC077]: 0x7d
            Sep 22 19:56:11 username AppName[20406]: DiskCookieStorage changing policy from 2 to 0, cookie file: file:///Users/username/Library/Developer/CoreSimulator/Devices/84839033-D772-4623-86AC-0F6599E4BB74/data/Containers/Data/Application/B1C5C134-6A92-4A55-A0E7-5E2929515FBB/Library/Cookies/Cookies.binarycookies
            Sep 22 19:56:12 username AppName[20406]: Apache Cordova native platform version 3.8.0 is starting.
            Sep 22 19:56:12 username AppName[20406]: Multi-tasking -> Device: YES, App: YES
            Sep 22 19:56:12 username AppName[20406]: Unlimited access to network resources
            Sep 22 19:56:12 username AppName[20406]:
            Sep 22 19:56:13 username AppName[20406]: [CDVTimer][splashscreen] 724.883020ms
            Sep 22 19:56:13 username AppName[20406]: [CDVTimer][keyboard] 0.113964ms
            Sep 22 19:56:13 username AppName[20406]: [CDVTimer][TotalPluginStartup] 725.518048ms
            Sep 22 19:56:14 username AppName[20406]: Resetting plugins due to page load.
            Sep 22 19:56:15 username AppName[20406]: Finished load of: file:///Users/username/Library/Developer/CoreSimulator/Devices/84839033-D772-4623-86AC-0F6599E4BB74/data/Containers/Bundle/Application/549DF5B3-A9A1-422D-A21E-732F5EB30147/AppName.app/www/index.html#/home

            (At this point, application home page is loaded as expected and I can go ahead use the application without any issues – expect there is no db created)

          • Are you trying to work with iOS 9 by chance (the latest)?

          • AP

            Developing on IOS 10.10.5 machine. Simulator IOS is 8.4 based on the logs.

            — ionice emulate ios —
            Building project : /Users/username/workspace/appName/appName/platforms/ios/AppName.xcodeproj
            Configuration : Debug
            Platform : emulator
            Build settings from command line:
            ARCHS = i386
            CONFIGURATION_BUILD_DIR = /Users/username/workspace/appName/appName/platforms/ios/build/emulator
            SDKROOT = iphonesimulator8.4
            SHARED_PRECOMPS_DIR = /Users/username/workspace/appName/appName/platforms/ios/build/sharedpch
            VALID_ARCHS = i386

            Build settings from configuration file ‘/Users/username/workspace/appName/appName/platforms/ios/cordova/build-debug.xcconfig’:
            CODE_SIGN_IDENTITY = iPhone Developer
            CODE_SIGN_RESOURCE_RULES_PATH = $(SDKROOT)/ResourceRules.plist

            === BUILD TARGET CordovaLib OF PROJECT CordovaLib WITH CONFIGURATION Debug ===

            Check dependencies

            === BUILD TARGET AppName OF PROJECT AppName WITH CONFIGURATION Debug ===

            Check dependencies

            PhaseScriptExecution Copy www directory build/AppName.build/Debug-iphonesimulator/AppName.build/Script-304B58A110DAC018002A0835.sh
            cd /Users/username/workspace/appName/appName/platforms/ios
            /bin/sh -c /Users/username/workspace/appName/appName/platforms/ios/build/AppName.build/Debug-iphonesimulator/AppName.build/Script-304B58A110DAC018002A0835.sh

            real 0m0.571s
            user 0m0.164s
            sys 0m0.297s

            ProcessInfoPlistFile build/emulator/AppName.app/Info.plist AppName/AppName-Info.plist
            cd /Users/username/workspace/appName/appName/platforms/ios
            export PATH=”/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/username/workspace/tools/gradle/bin:/Users/username/workspace/android-sdk-macosx/tools”
            builtin-infoPlistUtility /Users/username/workspace/appName/appName/platforms/ios/AppName/AppName-Info.plist -genpkginfo /Users/username/workspace/appName/appName/platforms/ios/build/emulator/AppName.app/PkgInfo -expandbuildsettings -format binary -platform iphonesimulator -additionalcontentfile /Users/username/workspace/appName/appName/platforms/ios/build/AppName.build/Debug-iphonesimulator/AppName.build/MainViewController-PartialInfo.plist -o /Users/username/workspace/appName/appName/platforms/ios/build/emulator/AppName.app/Info.plist

            GenerateDSYMFile build/emulator/AppName.app.dSYM build/emulator/AppName.app/AppName
            cd /Users/username/workspace/appName/appName/platforms/ios
            export PATH=”/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/username/workspace/tools/gradle/bin:/Users/username/workspace/android-sdk-macosx/tools”
            /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/dsymutil /Users/username/workspace/appName/appName/platforms/ios/build/emulator/AppName.app/AppName -o /Users/username/workspace/appName/appName/platforms/ios/build/emulator/AppName.app.dSYM

            Touch build/emulator/AppName.app
            cd /Users/username/workspace/appName/appName/platforms/ios
            export PATH=”/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/username/workspace/tools/gradle/bin:/Users/username/workspace/android-sdk-macosx/tools”
            /usr/bin/touch -c /Users/username/workspace/appName/appName/platforms/ios/build/emulator/AppName.app

            ** BUILD SUCCEEDED **

            No target specified for emulator. Deploying to iPhone-6 simulator
            ** RUN SUCCEEDED **

          • Weird!

            Just for the heck of it, can you try to insert data into it and see if it fails? Maybe it is not ending up where you think it is.

          • AP

            Hi Nic, thought I would give this a closure as I managed to fix the issue – for some reason my sqlite plugin wasn’t setup properly in my project. Once I did that, it started behaving better. Appreciate your help with this.

            Hope you don’t mind if I add another question to this – my program tends to proceed ahead without “waiting” for the response to my select queries. I assumed (from your example as well) that I don’t need to use ‘defer’ in order to make sure the program waits for the response before proceeding ahead.

          • Yea I hate it when Apache Cordova doesn’t install plugins correctly. Happens to me occasionally too.

            In regards to your second question, can you give me more information? I know I don’t explain it in this tutorial, but you probably don’t want to open your database via the run() method. I did it because my database is small and the odds were in my favor that it would open before hitting the controller. In reality you would probably want to have a setup controller / route and change states only after your application is setup.

            Does that answer the question?

      • Jim Harkins

        How can we find out the status of this Apache Cordova / Ionic Framework issues? Is there a work around for iOS 9 issues?

        • I don’t work for Apache Cordova or Ionic Framework. My best advice would be to track the Apache Cordova Jira channel and Ionic Framework forums.

          My guess is this issue won’t be corrected for another month since iOS 9 just came out.

          I’ve heard of people having success by altering the app transport security (ATS) of the app via Xcode.

  • vabs

    Hi Nic,
    I found the tutorial really helpful and It runs as per expectations for the first time on the device(android) but after quitting application when I rerun, it does not show the data that i am fetching from database.
    Please help me solve this problem.
    thanks,

  • Merwin De los Reyes

    Sir I’m having an error in the last part of your tutorial. i try to use the code “ionic add android” then it gives an error.

    Failed to find bower component “android”

  • PIUSH GUPTA

    Hi Nic
    Tried this in the app
    working fine with Android Version 4.4.2 and below
    but for version from 5.0.1 the app crashes showing an alert Unfortunately App has stopped.

    thanks

    • What do your logs say?

      • PIUSH GUPTA

        no error in logs

        their is an alert stating “Unfortunately App has stopped” when i try calling the page with the plugin

        in a device with android lollipop
        whereas for devices with android kitkat it works fine.

  • NIkita

    For both Android & iOS, Do I have to copy the .SQL file in both locations? Won’t this increase the size of the app?

  • NIkita

    I have this data at services.js and wants to use your pre-populated .sql instead. I’m at lost as to how I should go about it 🙁

    I’m fairly new to AngularJS and learning. If you could write me the code or point me to the right direction, it would be great.

    var employees = [
    {“id”: 1, “firstName”: “James”, “lastName”: “King”, “managerId”: 0, “managerName”: “”, “reports”: 4, “title”: “President and CEO”, “department”: “Corporate”, “cellPhone”: “617-000-0001”, “officePhone”: “781-000-0001”, “email”: “[email protected]”, “city”: “Boston, MA”, “pic”: “James_King.jpg”, “twitterId”: “@fakejking”, “blog”: “http://coenraets.org”},

  • NIkita

    Can anybody provide a working example of this tutorial?!
    I’ve been at it for nearly 2 days now and can’t get it to work at all 🙁

  • NIkita

    Also, how do i create a .db file? DB Browser for SQLite exports only in .sql or csv extension 🙁

    Also, let’s say i manage to get your tutorial going, What should i do to call the data into my app?!

    • SQL and CSV are not correct. You are either not saving the database correctly, or DB Browser no longer offers this. You don’t have to use DB Browser, it is only an example I threw out. You could use the command line if you really wanted to.

      As for loading the data into your application, I’ve outlined this numerous times through video and through write-up. You may want to take a step back and first research using SQLite in your application before you jump ahead and start looking at pre-populated databases:

      https://www.thepolyglotdeveloper.com/2014/11/use-sqlite-instead-local-storage-ionic-framework/

      Regards,

  • jeff de leon

    Hi Nic
    Tried your example its already working. My question is how to replace the existing sqlite db with another sqlite db with new tables. replacing the db from www folder did not work. Thank you

    • You need to delete the SQLite database on the device before trying to copy again.

      • jeff de leon

        Ok thanks. tried using
        window.sqlitePlugin.openDatabase({name: “tesdb”, createFromLocation: 1}). It worked!

        • Awesome! I had forgotten about that createFromLocation command 🙂

  • Arya Brammantyo

    Hi Nic. It’s an awesome tutorial you have. But I’m having some trouble here
    I have installed the plugins for SQLite and DBcopy and then following your tutorial. When I test it on the chrome with localhost it appears normal. But when I click the button the log says :
    Uncaught TypeError: Cannot read property ‘sqlDB’ of under undefined http://localhost:8100/js/app.js

    can you help out? Big thanks 🙂

    • I cannot stress this enough. Don’t use ionic serve, ionic view, or ionic live-reload to test your applications. I can see by http://localhost:8100 that you are using one of those methods for testing.

      If you assure me you are not using one of those services, then please paste your full ADB logs.

      Regards,

      • Arya Brammantyo

        Sorry i’m a total beginner about this. I have look up your another blog about testing ionic right here https://www.thepolyglotdeveloper.com/2015/02/properly-testing-ionic-framework-mobile-application/

        When i run command ionic build android I got
        Error : Please Install Android target : “android-22”
        and I’m a bit confused about this. I’ve run android.BAT and download the SDK but I think I’ve missing something
        Thanks for the help

        • That error is saying you don’t have the appropriate Android build tools installed. Open your Android SDK Manager and install Android API 22. If you prefer, I have a great beginner level course that you’d probably benefit from:

          https://www.udemy.com/ionic-framework-101-quickstart/?couponCode=GIMME5

          Promo code GIMME5 will get you 10% off.

          I designed it for beginners like you 🙂

          Best,

          • Arya Brammantyo

            Thanks a lot Nic it will be a big help for me learning this

          • No problem!

          • Arya Brammantyo

            Hi Nic, you’re telling me to take your course. Before I take it can I ask some question so that I will get what I need for my project. So my project is about making an real time-online app for reservation/booking like hotel or restaurant. Did your course will teach about the database, how to get or save data in database?or do you have any suggestion which course should I take? Thanks a lot for your help 🙂

          • Although my beginner course offers info about saving, it does not get into advanced concepts.

            If you consider yourself a beginner, it won’t hurt you to check it out. Look at the lecture titles so you know the topics it offers. https://www.thepolyglotdeveloper.com/courses/

            Regards,

  • Hridaya Kandel

    Hi Nic,

    i copied the database as below and it only works if i open database again outside window.plugins.sqlDB.copy as below
    is it the correct way

    window.plugins.sqlDB.copy(“krishighar.db”, function() {
    db = $cordovaSQLite.openDB(“krishighar.db” );
    }, function(error) {
    console.log(“Error Code = “+JSON.stringify(error));
    console.error(“There was an error copying the database: ” + error);
    db = $cordovaSQLite.openDB(“krishighar.db” );
    });

    db = $cordovaSQLite.openDB(“krishighar.db” );

  • Kamran Khan

    Hi Nic

    This is very nice step by step guide and very helpful, I used this same method and everything works first time fine,

    var ionicApp = angular.module(‘starter’, [‘ionic’, ‘starter.controllers’, ‘starter.services’, ‘ngCordova’]);

    var db = null;

    angular.module(‘ionicApp’, [‘ionic’])

    ionicApp.run(function($ionicPlatform, $cordovaSQLite, $rootScope) {

    $ionicPlatform.ready(function() {

    });

    })

    When I run first time this part is executed
    console.error(“There was an error copying the database: ” + error);

    db = $cordovaSQLite.openDB(“bible.db”);

    $rootScope.dba = db;

    but when when I close app and reopen it lost db connection and does not work, please I need your help. Thank you so much

    • Please only share code if I ask for it.

      What do your actual error logs say? Not the logging that you place within your code, but the device or simulator logs.

      Regards,

      • Kamran Khan

        Hi, Nic

        Thank you so much for help in advance, and for your respond. This is what I am getting in console log:

        TypeError: Cannot call method ‘transaction’ of undefined
        at Object.execute (file:///android_asset/www/lib/ngCordova/dist/ng-cordova.js:6378:12)
        at new (file:///android_asset/www/js/controllers.js:55:24)
        at invoke (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:12891:17)
        at Object.instantiate (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:12902:23)
        at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:16156:28
        at updateView (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:42695:30)
        at eventHook (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:42642:17)
        at Scope.$broadcast (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:21789:28)
        at $state.transition.resolved.then.$state.transition (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:35066:22)
        at wrappedCallback (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:20400:81)

        Regards,
        Kam

        • What is the snippet of code at line 55 of controllers.js?

          • cristian

            Hi Nic: thank! nice article, but everything works first time fine,
            but when I close app and reopen it lost db connection and does not work
            the code:

            app.js

            var example = angular.module(‘starter’, [‘ionic’,’ngCordova’]);
            var db = null;

            example.controller(“ExampleController”, function ($scope, $cordovaSQLite, $window, $ionicPlatform, $ionicPopup, $stateParams) {

            })

            index:

            Select All

            the log when i close and “rerun” the app and click the “selectall” button:
            TypeError: Cannot call method ‘transaction’ of null

            ionic.bundle.js (21162,24)

            Help me please, Thank you very much

          • Kamran Khan

            Nic thanks for reply, and I am sorry for late respond, here is the code snipet at starting from line 55

            $cordovaSQLite.execute(db, query, [$stateParams.chapid,$stateParams.bookId]).then(function(res) {

          • Try moving the database initialization logic into a controller rather than the module.run. You might be suffering from a race condition based on the size of your database. Module.run is asynchronous so maybe it is not finished loading before your app tries to access the data.

            Regards,

          • Kamran Khan

            Hi, this is great Nic it really worked, thanks

            God bless you man,
            Kamran

          • Awesome!

            Glad you got it working 🙂

          • Lucas Arcuri

            Hi everybody,

            for my part it was because the location parameter is not present:

            window.plugins.sqlDB.copy(dbname, location, success,error);

            it was from the sqlDBcopy doc : https://github.com/an-rahulpandey/cordova-plugin-dbcopy

            Best regards,

          • Thanks for reporting back 🙂

  • julia ibañez

    Hi Nic!

    I got the error “Error: [ng:areq] Argument ‘ExampleController’ is not a function, got undefined” I don’t know why. Can you help me? Thanks!

    • I’m going to take a wild guess here and say you either have a typo or you’re trying to use a controller like a function when you shouldn’t be.

      Can you provide your full logs?

  • Mahendra Kolhe

    ge sir plz solve this problem i got this error—->Uncaught TypeError: Cannot read property ‘sqlDB’ of undefined

  • Shankar Manoharan

    Hi Nic,
    I need to use, synchronously access sqlite database, difficulty I found in using loops. (not able to use sqlite queries within loops since loop gets iterated before the current sqlquery gets processed.

    I used angular.forEach for iterated record, its working fine in browser, but I make build apk file, Running in mobile device, value all undefined .

    I’m using Ionic framework, please help me.

  • Bernardo Gomes

    Hello people !
    I tried for many hours for it to work !! I put the name db.sqlite3 and it did not work . I changed and I put db.sqlite worked.

  • aceylan

    Hi Nic. Thank you for this tutorial. I have same problem from Kamran Khan. But i didnt understand solving. in the first time, software is working. But if i closed app and open again, it is not working. My codes; app.js

    // Ionic Starter App

    // angular.module is a global place for creating, registering and retrieving Angular modules

    // ‘starter’ is the name of this angular module example (also set in a attribute in index.html)

    // the 2nd parameter is an array of ‘requires’

    var ionicApp =angular.module(‘starter’, [‘ionic’,’ngCordova’]);

    var db = null;

    ionicApp.run(function($ionicPlatform, $cordovaSQLite) {

    $ionicPlatform.ready(function() {

    window.plugins.sqlDB.copy(“ogrenci.db”, function() {

    });

    });

    ionicApp.controller(“ExampleController”, function($scope, $cordovaSQLite) {

    });

    my index.html is

    Can you help me with code sample?
    Thanks a lot.

  • Nasrul Faizin

    Nice, How to implement database version?

    • Can you explain your goal? I don’t know what you’re talking about.

  • Swee Eng Khor

    hi,

    I have the following code, and tested in the a android device. Somehow the erorr is showing “OK”
    May I know what is the problem ?

    window.plugins.sqlDB.copy(“School.db”, function () {
    alert(‘Sucess’);
    db1 = $cordovaSQLite.openDB(“School.db”);
    }, function (error) {
    alert(“There was an error copying the database: ” + JSON.stringify(error));

  • Loralon81

    Hi,

    i have a strange problem with this code…everything works first time but when i close app and reopen it doesn’t work.

    The log: no such table: table_name

    ?!? i don’t change anythings…what’s happened?!…i used DB Browser for SQLite to create the DB…but the DB “in APP” seems to be empty…

    Please Help me

    • I need more information. What do your full logs say? What platform are you using? What versions? The more info I have the better I can help.

      • Loralon81

        Thanks for repling.

        Cordova 5.4.1
        testing on iOS 8.2

        i’m using the ionic server console…

        log OPEN database: terreolio.db
        log DB opened: terreolio.db
        error no such table: sabina ( console.error(err.message);)
        error [object Object] ( console.error(err);)

        the logs above when i try to query db

        if i change somethings in app.js and save:

        0 406922 error Error: null is not an object (evaluating ‘n.transaction’)
        [email protected]://192.168.1.132:8100/js/ng-cordova.min.js:9:17965
        http://192.168.1.132:8100/js/app.js:142:31
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:13282:22
        http://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:17831:40
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:16941:46
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:16373:23
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:16977:35
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:16373:23
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:16248:45
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:52345:11
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:50456:58
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:50376:26
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:52198:18
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:52156:16
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:57577:31
        http://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:57561:19
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:17482:15
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:16982:23
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:16373:23
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:16248:45
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:58944:37
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:24515:31
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:24783:31
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:10465:21
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:13282:22
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:10463:20
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:10483:23
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:10377:14
        http://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:37191:16
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:11828:9
        [email protected]://192.168.1.132:8100/lib/ionic/js/ionic.bundle.js:12103:25,

        LINE 142:

        var query = “SELECT * FROM sabina”;
        $cordovaSQLite.execute(db, query, []).then(function(res) { —> 142
        if(res.rows.length > 0) {
        for(var i = 0; i < res.rows.length; i++) {
        console.log(“SELECTED -> ” + res.rows.item(i).nome_it);
        $scope.itinerari.push({
        nome_it: res.rows.item(i).nome_it,
        nome_en: res.rows.item(i).nome_en,
        telefono: res.rows.item(i).telefono
        });
        $scope.$apply();
        }
        } else {
        console.log(“No results found”);
        }
        }, function (err) {
        console.error(err);
        });

        • Loralon81

          Waiting for you i tried some other things…no result…

          https://github.com/Loralon/Olio.git

          • Rule #1, don’t try to get my attention with more comments asking for me. I’m not on the same timezone as you, and you aren’t the only one asking for help. I’ll get to your questions when I can.

            With that out of the way, stop using Ionic Serve. It does not work correctly with native plugins. I don’t use them in my tutorials or videos and neither should you.

            Regards,

          • Kervin Avila

            i have the same problem, at first everything works fine but when i close it and reopen the app just loading, i install it in my android jellybean. pls help

  • Juan Camilo Herrera

    Hi Nic, I did exactly what you did (with my own data-base, it has 31 tables) but when I run it in Google Chrome appears this error (Uncaught TypeError: Cannot read property ‘sqlDB’ of undefined) and also the one that says that it couldn’t find cordova.js but I think that one is normal, can you help me please?

    • You cannot use the web browser when you use native plugins. This is why you’re getting these errors.

      Regards,

      • Juan Camilo Herrera

        Thanks for your prompt answer, I did it and it worked, but after I tried it on iOs and it doesn’t even open the database and it generates issues in the sqlite3.c file and also in the AppDelegate.m file could you help me please?

        AppDelegate.m

        /Applications/MAMP/htdocs/IonicProject/platforms/ios/HelloCordova/Classes/AppDelegate.m:138:1: Conflicting return type in implementation of ‘application:supportedInterfaceOrientationsForWindow:’: ‘UIInterfaceOrientationMask’ (aka ‘enum UIInterfaceOrientationMask’) vs ‘NSUInteger’ (aka ‘unsigned long’)

        sqlite3.c

        /Applications/MAMP/htdocs/IonicProject/platforms/ios/HelloCordova/Plugins/cordova-sqlite-storage/sqlite3.c:25368:6: “gethostuuid() is disabled.”

        /Applications/MAMP/htdocs/IonicProject/platforms/ios/HelloCordova/Plugins/cordova-sqlite-storage/sqlite3.c:26752:14: Implicit conversion loses integer precision: ‘ssize_t’ (aka ‘long’) to ‘int’

        /Applications/MAMP/htdocs/IonicProject/platforms/ios/HelloCordova/Plugins/cordova-sqlite-storage/sqlite3.c:28471:42: Implicit conversion loses integer precision: ‘unsigned long long’ to ‘int’

        /Applications/MAMP/htdocs/IonicProject/platforms/ios/HelloCordova/Plugins/cordova-sqlite-storage/sqlite3.c:28634:11: Implicit conversion loses integer precision: ‘ssize_t’ (aka ‘long’) to ‘int’

        and more issues but the weird thing is that it doesn’t show any error in my log

        • Well it looks like you’re trying to save a value of type long to type int. What is the value of ssize_t and what is the column expecting?

          • Juan Camilo Herrera

            I realize that the platform iOs wasn’t loaded in the xml so it couldn’t work, after that I tried to run it once again but now it doesn’t show any issue or something, nothing in console but it doesn’t run in my xCode, it just run with Cordova from the terminal but still doesn’t load my data-base but in android it works perfect!

          • Try removing the plugin and installing it again? And try uninstalling the old app from your iOS simulator and starting fresh?

            If it works in Android, it should work in iOS. Did you follow the instructions correctly on how to include the database in your project?

          • Juan Camilo Herrera

            I did all again, I create the project once again empty and then I put the whole code but still works in android but not in iOS, I follow the instructions correctly I’m sure, I located the data base in www folder, platforms/iOS/project-name/resources and in android assets

          • Per the plugin documentation it needs to be in your www folder:

            https://github.com/an-rahulpandey/cordova-plugin-dbcopy#database-file-location

            I’m not sure what you’re doing with platforms/ios/project-name/resources as that is meaningless here.

          • Juan Camilo Herrera

            you are right I just need to put it into my www folder, I solved it today the problem was that the plugin works perfect with android adding it normal but with iOS I had to remove iOS platform and add it again because the iOS platform is added automatically, thanks for your help, really good video and explanation

          • Juan Camilo Herrera

            Sorry for writing twice but I got an other problem and I already tried every solution I found and it doesn’t work, I need to put the result of the DB search in a select in html, I got it but just using an ng-click=”select()” but the thing is that I want it to load with the page so I tried the ng-init=”select()” but it does the DB search before load the database so it doesn’t work and if I put it like this … it does the DB search on time but it fills the select options after showing them so it doesn’t work I don’t know how can I solve this

  • maxpom

    Hello!
    I had a problem, my existing db was not open so a new db was created.
    I solved my problem by removing .db database in cordova and in app.js.

    window.plugins.sqlDB.copy(“populated”, function() {
    db = $cordovaSQLite.openDB(“populated”);

    in cordova project my db is “populated”.

  • O. Caballero

    Hi, your blog is very nice, I learn to create applications with ionic but now I need download the database remote but the data is in the API rest , the steps that I need execute are:

    1) When the application run I need check a version DB

    2) read the data and insert in my database sqlite

    3) redirect and create the list with the new data

    but when run the application say Cannot call method ‘transaction’

    • Please paste the full logs.

      Regards,

  • Shantanu Acharya

    Hi Nic,

    I am following your tutorials regarding Ionic framework, Everything you have provided is of great help to the Ionic community. I have followed your tutorial regarding cordovaSqlite plugin https://www.thepolyglotdeveloper.com/2014/11/use-sqlite-instead-local-storage-ionic-framework/ it worked and I implemented same into my project that was also working, but as I made an environmental setup on diff machine cordovaSqlite plugin does not work, I have again followed your tutorial it also has same problem, debugged it into avd with command: ionic run android -l -c and got ( error Uncaught TypeError: Cannot read property ‘openDatabase’ of undefined, http://192.168.2.10:8100/js/ng-cordova.min.js, Line: 9 )

    • When I see http://192.168.2.10:8100 I know for a fact you’re doing it wrong. This is because of live reload.

      You need to build and install the applications. When you have native plugins in your app, services like ionic serve, ionic live reload, ionic view, phonegap build, etc., will not work correctly.

      Regards,

  • Eren

    Hey, nic! i have to say i love your tutorials. keep it up. Here is my problem i have placed my database in to www folder(same folder with index.html).

    Almost 3-4 hours of research i couldn’t find any solution to my problem. Database doesn’t get copied to the device and because of that gives an error

    and creates new database itself. I am using Genymotion v4.4.4 emulator(also tried my phone which is v4.4.2). I need your help :), have a nice day.

    here is my app.js file

    var myapp=angular.module(‘tvsa’, [‘ionic’, ‘tvsa.controllers’, ‘tvsa.routes’, ‘tvsa.services’, ‘jett.ionic.filter.bar’, ‘ngCordova’]);

    var db=null;

    myapp.run(function ($ionicPlatform, $cordovaSQLite) {

    })

    And here is my logcat report.

    D/SystemWebViewEngine( 3771): CordovaWebView is running on device made by: Genymotion

    D/dalvikvm( 3771): GC_FOR_ALLOC freed 2795K, 48% free 3250K/6204K, paused 7ms, total 7ms

    I/dalvikvm-heap( 3771): Grow heap (frag case) to 9.185MB for 6144012-byte allocation

    D/dalvikvm( 3771): GC_CONCURRENT freed <1K, 25% free 9250K/12208K, paused 2ms+1ms, total 6ms

    D/dalvikvm( 3771): WAIT_FOR_CONCURRENT_GC blocked 3ms

    V/StatusBar( 3771): StatusBar: initialization

    W/EGL_genymotion( 3771): eglSurfaceAttrib not implemented

    E/OpenGLRenderer( 3771): Getting MAX_TEXTURE_SIZE from GradienCache

    E/OpenGLRenderer( 3771): MAX_TEXTURE_SIZE: 16384

    E/OpenGLRenderer( 3771): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()

    E/OpenGLRenderer( 3771): MAX_TEXTURE_SIZE: 16384

    D/OpenGLRenderer( 3771): Enabling debug mode 0

    W/EGL_genymotion( 3771): eglSurfaceAttrib not implemented

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    I/ActivityManager( 583): Displayed com.ionicframework.tvseriesarchiver519587/.MainActivity: +854ms

    D/JsMessageQueue( 3771): Set native->JS mode to OnlineEventsBridgeMode

    V/StatusBar( 3771): Executing action: _ready

    I/chromium( 3771): [INFO:async_pixel_transfer_manager_android.cc(60)] Async pixel transfers not supported

    I/chromium( 3771): [INFO:async_pixel_transfer_manager_android.cc(60)] Async pixel transfers not supported

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    V/StatusBar( 3771): Executing action: styleDefault

    I/chromium( 3771): [INFO:CONSOLE(23)] “copying”, source: file:///android_asset/www/js/app.js (23)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    I/Choreographer( 3771): Skipped 38 frames! The application may be doing too much work on its main thread.

    D/dalvikvm( 3771): Trying to load lib /data/app-lib/com.ionicframework.tvseriesarchiver519587-1/libsqlc-native-driver.so 0xa5068fd0

    D/dalvikvm( 3771): Added shared lib /data/app-lib/com.ionicframework.tvseriesarchiver519587-1/libsqlc-native-driver.so 0xa5068fd0

    D/dalvikvm( 3771): No JNI_OnLoad found in /data/app-lib/com.ionicframework.tvseriesarchiver519587-1/libsqlc-native-driver.so 0xa5068fd0, skipping init

    V/SQLitePlugin( 3771): Android db implementation: default-NDK

    V/info ( 3771): Open sqlite db: /data/data/com.ionicframework.tvseriesarchiver519587/databases/test.db

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    D/MobileDataStateTracker( 583): default: setPolicyDataEnable(enabled=true)

    I/chromium( 3771): [INFO:CONSOLE(28)] “There was a error copying database: “OK””, source: file:///android_asset/www/js/app.js (28)

    I/chromium( 3771): [INFO:CONSOLE(174)] “OPEN database: test.db”, source: file:///android_asset/www/plugins/cordova-sqlite-storage/www/SQLitePlugin.js (174)

    I/chromium( 3771): [INFO:CONSOLE(79)] “DB opened: test.db”, source: file:///android_asset/www/plugins/cordova-sqlite-storage/www/SQLitePlugin.js (79)

    D/dalvikvm( 583): GC_CONCURRENT freed 1981K, 33% free 11710K/17476K, paused 0ms+1ms, total 8ms

    • The database will only copy if one does not exist. My assumption is you tried to add and test this code after a database was already put in place.

      Am I right?

      • Eren

        yes, it doesn’t work, i always did delete my data and my application. i tried almost every solution in here. someone mention that delete the ‘.db’ in expressions. I did olso try that. it doesn’t work. i created my database with sqlitebrowser. i mean i don’t know what to do.

      • Eren

        thank you for the response and awesome tutorials again. i solved my problem, i moved my copy code to my home page controller. and it still didn’t work. so i used the following;
        window.plugins.sqlDB.copy(“test.db”,0, function(){
        db = $cordovaSQLite.openDB(“test.db”);

        and it did work finally 🙂

  • Hello Nic..
    I have try this tutorial and it succeed.
    But I wonder how to show those data in my html?
    I have try to push(res.rows.item(i)) to my variable, and when I call it on html with {{variable.firstname}} it won’t show anything.

    Thanks.

    • You should print the data to your logs first to make sure you are even getting results.

      • Hi.. I finnaly got it works..
        I use $scope.variable.push(res.rows.item(i)) to throw the data into my variable

        Thanks anyway 😀

  • Hi Nic,
    I have a problem when I use $urlRouterProvider.otherwise(‘mystate’);
    I want to load mypage at mystate at first launch of my app, but it seems the $urlRouterProvider.otherwise can’t reach $cordovaSQLite.execute …

    But when I go to mypage via button ui-sref=”my-page”, it just works, I got my data from database.
    Do you have some advise for me?
    thanks.

    • Sounds like you don’t have a firm understanding of how the UI-Router works. I suggest reading up on it. You should also consider making an Angular service for database transactions.

  • Vishal

    Only First Time Its Run Completly Then After every Time It Shows The Error db.transaction is not a function
    I am stuck at this from 3 days will you please help me

    • What do your full logs say?

      • Vishal

        Actually It Gives Error When DB File Exists And sqldb copy function goes in error call back every time it gives an error db.transaction is not a function

        • I won’t be responding to you again without seeing your logs. This is the second time I asked.

  • Indika Ratnayake

    Hi Nic, what if we do changes/updates to the database using the app. How do you save those changes in the original DB?

    • The application will not make changes to the original bundled database, only the copy. The whole purpose of this is to ship a database filled with data so users don’t have to spend an hour downloading initialization data when they first start your application. Should you need to ship further initialization data, your new users should get that with the pre-filled database and existing users get the small changes via a network connection.

      Regards,

  • multilexus

    Hi Nic,

    I created my own sqlite database in windows called test.db, which contains table “people”, just like your example above, and it looks like it copied successfully to my android device. The log says “DB opened: test.db”. But when I try to run your “select” method on it, the log shows error: “Object {message: “no such table: people (code 1): , while compiling:…#################################################”, code: 0}”.

    That doesn’t make any sense to me as in windows I can open my test.db and view both tables that it contains, one of them being “people”. Any suggestions?

    Best regards,
    Alex S.

    • What version of SQLite? Android uses a much older version so I’m wondering if there is a versioning conflict between your Windows environment and Android.

  • Nadir Bertolasi

    Hi nic,

    I get this problem:

    error TypeError: Cannot read property ‘transaction’ of null
    at Object.execute (http://192.168.0.10:8100/js/ng-cordova.min.js:9:19174)

    I think it is due to the fact that home controller is launched before that copy is finished.

    This is my code:

    app.run(function($ionicPlatform, $cordovaSQLite) {
    $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }

    });

    app.controller(‘HomeCtrl’, function($scope, $rootScope, $cordovaLaunchNavigator, $cordovaSQLite) {

    var query = “SELECT name FROM monument”;
    $cordovaSQLite.execute(db, query, []).then(function(res) {
    if(res.rows.length > 0) {
    for(var i = 0; i < res.rows.length; i++) {
    console.log(“SELECTED -> ” + res.rows.item(i).name);
    }
    } else {
    console.log(“No results found”);
    }
    }, function (err) {
    console.error(‘Error executing Query!’);
    console.error(JSON.stringify(err));
    });

    I also have seen that commenting query code on HomeCtrl I don’t get any error, but also I see that console.log(‘db copy completed’);
    I think that my copy doesn’t complete and remains appended.

    Can you please help me?

    Thanks

  • Prithvifb Chauhan

    Hello Nic,
    Nice tutorial but have one issue cordovaSQLite working great with android and ios but with blackberry it is not working. Does this plugin made for blackberry also i am using blackberry Z10.

    • I don’t know anything about blackberry. It is a dying platform. Best save yourself the trouble and stay away from it

  • Lisa

    Hi Nic,
    please help me!
    I trying to create my first app and I can not read a prefilled SQLite DB.
    I am a beginner and I can not even see properly console.log. I know only ionic serve e ionic run command to see my app and I add alert in your code but is not the same…

    My code is simple:

    app.js –>
    var db = null;
    angular.module(‘starter’, [‘ionic’, ‘ngCordova’, ‘starter.controllers’])
    .run(function ($ionicPlatform, $cordovaSQLite) {
    $ionicPlatform.ready(function() {
    if (window.cordova && window.cordova.plugins.Keyboard) {
    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    cordova.plugins.Keyboard.disableScroll(true);
    }
    if (window.StatusBar) {
    // org.apache.cordova.statusbar required
    StatusBar.styleDefault();
    }

    });

    })

    –> controller.js

    .controller(“ExampleController”, function ($scope, $cordovaSQLite) {
    alert(‘ccc’);
    $scope.selectAll = function () {
    var query = “SELECT nome FROM categorie”;
    $cordovaSQLite.execute(db, query, []).then(function (res) {
    if (res.rows.length > 0) {
    for (var i = 0; i < res.rows.length; i++) {
    alert(“SELECTED -> ” + res.rows.item(i).nome + ” “);
    }
    } else {
    alert(“No results found”);
    }
    }, function (err) {
    alert(‘err’);
    console.error(err);
    });
    }
    });

    My db have one table, categorie with ‘id’ and ‘nome’.

    When I run the app on my device, I can see only ‘ccc’ alert?

    What can I do to do a better debug and understand my problem?
    I try to read your article ‘Debugging Your Android Source Code With ADB’, but I do not understand the command sequence…

    Excuse my ignorance but I am a newbie!!!! 🙁

  • vimesh

    am getting this error when i was trying to copy db from asset folder….anyone pls help me
    java.lang.Error: Create Database Exception ============================ java.io.FileNotFoundException: www/itemmanger.sqlite

    E/AndroidRuntime(27743): at me.rahul.plugins.sqlDB.DatabaseHelper.createdatabase(DatabaseHelper.java:30)

    E/AndroidRuntime(27743): at me.rahul.plugins.sqlDB.sqlDB$1.run(sqlDB.java:88)

    E/AndroidRuntime(27743): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

    E/AndroidRuntime(27743): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

    E/AndroidRuntime(27743): at java.lang.Thread.run(Thread.java:841)

    W/ActivityManager( 581): Force finishing activity com.ionicframework.itemmasterapp800053/.MainActivity

    V/SQLitePlugin(27743): Android db implementation: built-in android.database.sqlite package

    V/info (27743): Open sqlite db: /data/data/com.ionicframework.itemmasterapp800053/databases/itemmanger.sqlite

    D/dalvikvm( 581): GC_FOR_ALLOC freed 183K, 25% free 7002K/9312K, paused 13ms, total 13ms

    • This is the line that seems to matter:

      java.lang.Error: Create Database Exception ============================ java.io.FileNotFoundException: www/itemmanger.sqlite

      Seems like you may have placed your pre-filled database in the wrong location.

      Best,

  • mahaboob baig

    Hi Nic, i tried this code but not getting any result. see my code below.

    var db = null;

    angular.module(‘starter’, [‘ionic’, ‘sqlite.controller’, ‘ngCordova’])

    .run(function ($ionicPlatform, $cordovaSQLite) {

    })

    My controller

    var myApp = angular.module(‘sqlite.controller’, []);

    myApp.controller(‘readDbCtrl’, function ($scope, $cordovaSQLite) {

    $scope.getData = function () {

    }

    });

    please help me, what is wrong in my code

      • mahaboob baig

        db = $cordovaSQLite.openDB(“grocery.db”);
        in this line i am getting error. i unable to open database. it returning db = null.

        • You didn’t get me the information I needed:

          What platform are you using? Is this a device or a simulator? Are you trying to use Ionic Serve? What do your full logs say? Etc.

          I don’t have enough information to help you. I’m referring you back to re-read the blog post I linked you in the previous comment regarding seeking help.

          Regards,

          • mahaboob baig

            i am using android platform. i am using device.

            window.plugins.sqlDB.copy(“groce.db”, 0, function () {
            $cordovaToast.showShortTop(‘db copied’);
            db = $cordovaSQLite.openDB(“groce.db”, 0);
            $cordovaToast.showShortTop(‘db opened’);
            }, function (error) {
            $cordovaToast.showShortTop(“Error ” + error);
            });
            i am getting ‘db copied’ toast. but not getting ‘db opened’ toast.
            if i use ionic serve i am getting below error

            ionic $ 0 840973 error Uncaught TypeError: Cannot read property ‘sqlDB’
            of undefined, http://localhost:8101/js/app.js, Line: 17

          • mahaboob baig

            Hi Nic, Thanks .This code is working for me. But i am inserting data, query is executing but data is not inserted in table. how to insert data?

  • Saifuddin

    I want to use a pre-populated in my ionic app for android and iOS. i have done all stuff according to your tutorial, but it does’t work on simulator. could you please help me on how to do that? if you have any new tutorial or suggestion please let me know. thanks

  • keranbin

    Hi Nic , you are so cool ,I need your help ,please,this is my code

    console.log(“begin to copy”);

    and this is the cosole

    begin to copy app.js:26

    null app.js:44

    TypeError: Cannot call method ‘transaction’ of null

    I don’t not why the console.log(db) result is null ,is it fail to copy the db?

    • Can you validate that db is actually set before trying to use it?

      • keranbin

        can you copy a simple test demo to me ,Thanks

        • Sorry I don’t package my source code for any of my free material. The write-up and video should be enough to go off of. Specially since my video is step by step from zero to finish.

          Best,

          • keranbin

            ok,I will see it again,thanks,nic

  • Veeraj Shenoy

    sometimes my data loads perfectly fine and other times I get ionic.bundle.js:25642 TypeError: Cannot read property ‘transaction’ of null this error

  • Veeraj Shenoy

    yay! solved just pasted my code under

    $ionicPlatform.ready(function() {}) inside a controller and voila! it now works everytime

  • vijay

    Hi Nic
    My question is how to replace the existing sqlite db with sql server db with new tables.

    • You’d have to create an API server and implement your own sync if you wish to copy data from a SQL Server database. Or you can toss out SQL Server and use something like Couchbase that has its own sync built in.

  • ashraful haque

    We want Ionic2

  • Paula

    ello I’ve been doing an example with this tutorial but not get it to work me. Could I provide the full code? I would greatly appreciate it, thank you very much

    • Sorry, but I don’t provide a bundle of the source code for my free content. The tutorial and step by step video should be more than enough for you.

      Best,

  • Mustard Dunbar

    Hi, I have attempted your example. I have tried the “cordovaSQLite.execute for a SELECT statement just to pull an ID value from my “TAGIT.db”.(Im sure that database was made correctly and is stored in the www directory). For some reason when I use logcat the log says TypeError Cannot call method of transaction. I am using geny motion emulator for testing. If you need any more information I’ll be happy to provide it. Thanks for reading

    • Mustard Dunbar

      Nic, I have found why my project wasn’t working. It was because of my window.plugins.sqlDB.copy. I did not include the location parameter (0 in my case). Lesson learned: Read the Github documentation for the specific plugin before posting the issue 🙂

  • Zubin Raja

    Tried it all in all possible ways. Its not working. Is there any parameter updated?

    • It’s not working doesn’t help me much. What isn’t working and what do your logs say?

  • Fadi Yousef

    Hi Nic,

    can you please make a tutorial for ionic 2?

  • Pria Ahuja

    Hi Nic..The article is of big help..However can you please me help in an issue i am getting going with the same approach.
    Whenever i try to close the app seems like db is getting deleted as i m getting db = null .Please guide.

  • Plugin is Amazing and with little tweaking, it worked like a charm.

    Just need one option.
    We need to check the database version before updating, This works very well for first time installation. But subsequently if you update the database and update the application , the database does not get updated and we have to uninstall , then reinstall the application for the new database to be used.

    Do we have option to check database version and update if necessary
    thanks

    • This is a one time copy for new installs. Database updates should be done via script for anyone who has already installed the application.

  • matt downing

    Hi Nic, this tutorial work fine for me.

    I wonder. when I call db outside window.plugins.sqlDB.copy return null?
    second log is file already exists on the location, I don’t know what first log mean

    LOG:
    I/chromium( 3538): [INFO:CONSOLE(34)] “|||||->> $ionicPlatform.ready >>||null”,
    source: file:///android_asset/www/js/app.js (34)

    I/chromium( 3538): [INFO:CONSOLE(31)] “|||||->> window.plugins.sqlDB.copy Error

    || {“openargs”:{“name”:”populated.db”,”location”:”default”,”dblocation”:”nosyn
    c”},”dbname”:”populated.db”}”, source: file:///android_asset/www/js/app.js (31)

    CODE:
    window.plugins.sqlDB.copy(“populated.db”, 0, success, error(){
    console.log(“|||||->> window.plugins.sqlDB.copy Error >>|| ” + JSON.stringify(db));
    });
    console.log(“|||||->> $ionicPlatform.ready >>||” + JSON.stringify(db));

    • Posting the same question on three different posts is not cool. I get an email for every comment made on my blog, as do other people as well.

  • Mustard Dunbar

    Hi Nic, Your database tutorial has really helped me towards my senior project construction. I want to make sure to give you your deserved credit in my code. Can you give me an example of how to achieve this?

    • I’m glad it was able to benefit you.

      If you’re giving a presentation to your classmates or teachers, the proper way would be to have a slide of references where you captured your source material. Of course this is usually only relevant if you’re showing off your code. If you’re showing off an app without digging into the code, you don’t need to list my site.

      The code you submit as part of the project should probably have a comment or file showing where you found your source material.

      Good luck 🙂

  • fjleon

    Hi Nic, i tried running your example but it doesn’t work, it says: Cannot read property ‘transaction’ of null
    at Object.execute (file:///android_asset/www/js/ng-cordova.min.js:9:23736)
    at Scope.$scope.selectAll (file:///android_asset/www/js/app.js:33:24). Line 33 is:

    $cordovaSQLite.execute(db, query, []).then(function(res) {.

    I am using cordova-sqlite-ext as plugin. Full app.js at http://pastebin.com/22FBJgqC

    • fjleon

      i just saw that the dbcopy plugin had its api changed and now you need to pass a new parameter. After i did, now the error is:
      Error in Success callbackId: sqlDB951999623 : ReferenceError: $cordovaSQLite is not defined. I am using ionic run android against genymotion which emulates a real device

  • k3x

    Hi Nic.
    How to do this on ionic 2? I’m using SQLite from ionic-native but don’t know how to use the File plugin to copy the database.

  • Hi Nic!
    I want to send a report..
    In my case I should call database name and location parameter in db init like >
    db = $cordovaSQLite.openDB({ name: “mysqlite.db”, location: ‘default’ });

  • Akash

    Hi Nic

    ionic.bundle.js:26794 TypeError: Cannot read property ‘transaction’ of null
    at Object.execute (ng-cordova.min.js:9)
    at Scope.$scope.select (app.js:43)
    at fn (eval at compile (ionic.bundle.js:27638), :4:224)
    at ionic.bundle.js:65427
    at Scope.$eval (ionic.bundle.js:30395)
    at Scope.$apply (ionic.bundle.js:30495)
    at HTMLButtonElement. (ionic.bundle.js:65426)
    at defaultHandlerWrapper (ionic.bundle.js:16787)
    at HTMLButtonElement.eventHandler (ionic.bundle.js:16775)
    at triggerMouseEvent (ionic.bundle.js:2953)(anonymous function) @ ionic.bundle.js:26794(anonymous function) @ ionic.bundle.js:23507$apply @ ionic.bundle.js:30500(anonymous function) @ ionic.bundle.js:65426defaultHandlerWrapper @ ionic.bundle.js:16787eventHandler @ ionic.bundle.js:16775triggerMouseEvent @ ionic.bundle.js:2953tapClick @ ionic.bundle.js:2942tapMouseUp @ ionic.bundle.js:3018

    and my app.js line no. 41 to 52 is :

    $scope.select = function(lastname){
    var query = “SELECT firstname, lastname FROM people WHERE lastname=?”;
    $cordovaSQLite.execute(db, query, [lastname]).then(function(result){
    if(result.rows.length > 0){
    alert(“selected : “+result.rows.item(0).firstname+ ” “+result.rows.item(0).lastname);
    }else{
    alert(“no rows”);
    }
    },function(error){
    alert(“error : “+error);
    });
    }

    • How are you testing? Are you using a device or emulator? Are you trying to use ionic serve / ionic live-reload / ionic view? Please give me more details

      Best,

      • Akash

        Hi Nic this issue will solve when my sqlite query insert in try block

        • Jigar B Lodaya

          Could u help me out i am using prefilled db and when i try to select from db i am getting the same error.

          thank you.

  • Akash

    Hi Nic
    As per our discussion :
    I am using micromax device & test using android studio direct connect with usb debugging mode and run then show those errors.

    • Try moving all the database initialization code outside of the .run method and into its own controller. You might be suffering from a race condition.

  • Cool Ab

    Hi Nic, your tutorials are very helpful. Keep up the good work.
    Can you make a tutorial on how to use a pre-populated SQLite database in ionic 2?

    I have checked the ionic 2 documentation, and there is no enough information regarding this. The forums are not helpful too. Everyone is complaining about it.

  • Thail

    Hi Nic,

    I’m having errors while running this code.

    HERE is the ERROR i get. Please help me with this.

    app.js:28 Uncaught TypeError: Cannot read property ‘sqlDB’ of undefined

    • Did you find any solution to this ? I am also facing the same issue.

      • Omar Cruz

        Did you find any solution to this ? I am also facing the same issue. ???

  • sufiyan khan

    Hi Nic,
    I followed your SqLite tutorial and it worked like a charm.So very nice tutorial,I followed all steps of this tutorial.

    but i am getting an error as

    There was an error copying the database: {“message”:”File already exists”,”code”:516}

    these are the steps that did.
    1) I pasted the file as “populated” (and not “populated.db” as i assumes “db” is an extension) in platformsandroidassets
    2) tried to copy the db as window.plugins.sqlDB.copy(“populated.db”,1, function() {…

    Did i miss any step ? or is there code error??

  • koundou

    Very good Tutorial. I try to make it step by step but not work.i receive error that cannot cope the database.Is it possible download the files from somewhere?

    • I only include project archives within my premium articles.

      Best,

  • Mihir Patel

    Hey Nic,
    i can not see my apps package name or database created with sqlite, i got data back i can add new data in to table but i cant found database or package name on my device.
    help me if you have any solution

    • Apps and databases are stored in protected storage. Unless you have a rooted or jail broken device, you’re not going to find them.

      • Mihir Patel

        thanks for reply @nicraboy:disqus .

  • Mustard Dunbar

    I’ve been trying to research everywhere for this issue:

    What if I want to deploy a new app with an updated sqlite db.(using ionic’s deploy code)
    without having to uninstall the app then reinstalling it.

    (Sorry I posted a similar issue in ionic but got no guidance from anyone yet)
    Thanks for your time, if you need any more information from me I will gladly provide it.

  • Jigar B Lodaya

    Hey Nic Nice set of tutorials, Thanks.

    Right now my doubt is where should i copy my database file for ios? i am not having my project folder like u said here : platforms/ios/IonicProject/Resources : i am not having my project folder and not able to find the resources folder.

    Also should we be storing the database file in assets/www/file.db or assets/file.db for android

    Thanks for ur help 🙂

    • Per the plugin documentation, it now recommends in the www folder:

      https://github.com/an-rahulpandey/cordova-plugin-dbcopy#database-file-location

      Best,

      • Jigar B Lodaya

        Thanks, will try it out tomorrow and revert back 🙂

      • Jigar B Lodaya

        I am haivng trouble with this code snippet $cordovaSQLite.execute it says

        SystemWebChromeClient(18469): file:///android_asset/www/lib/ionic/js/ionic.bundle.js: Line 26799 : TypeError: Cannot read p
        roperty ‘transaction’ of null
        D/SystemWebChromeClient(18469): at Object.execute (file:///android_asset/www/js/ng-cordova.min.js:9:23736)
        D/SystemWebChromeClient(18469): at Scope.$scope.selectAll (file:///android_asset/www/js/app.js:51:20)