Use SQLite Instead of Local Storage In Ionic Framework

Switching to object-based data storage can often be tough.  If you’re trying to start Phonegap or Ionic Framework development and are coming from native development, the whole local storage concept can be a tough one to grasp.  Or maybe you just prefer a structured query language (SQL) when working with your data.

Not to worry, because there is a plugin for that!

Making use of the Cordova SQLite plugin by Chris Brody, you can use a SQLite data source for managing your data in Android and iOS.  Pair this with ngCordova and you can better compliment your Ionic Framework development with an AngularJS experience.

If you’re using Ionic 2, you should check out this tutorial instead.

Like with all my tutorials, let’s start by creating a fresh Ionic project:

Remember, if you’re not on a Mac computer, you cannot add and build for the iOS platform.

The next thing we want to do is add the SQLite plugin.  This can be done by running the following command:

Because this is an Ionic Framework article, we’re going to make use of ngCordova as it tends to make life pretty easy after including it.

Download the latest release and copy ng-cordova.min.js into your www/js directory.

With the library file included, we now need to include it in our project.  Open your index.html file and add the following highlighted line:

It is very important you add it above the cordova.js line otherwise it will not work.

One more thing must be added before we can start using ngCordova.  We need to inject it into our angular.module, found in app.js, like the following:

It’s time to start using this library.  For simplicity, we are going to do the following:

  1. Create a new table called people
  2. Insert two people into this new table
  3. Select all the people found in our table with my last name

Before we start coding, it is very important to note that database activity can only be done when the onDeviceReady() method has fired.  With this in mind, I’m going to open the database in the modules .run() method like so:

Take a look at the lines that I highlighted.  We want to have access to the database globally so I created a variable outside of any method or controller.  To use the ngCordova functions we need to include $cordovaSQLite in the .run() method.  Finally, you can see that I’ve created a new database called my.db and a fresh table called people.

This leaves us with a usable database ready for activity in our controllers.  Take the following for example:

I’ve gone ahead and created two very basic functions.  The insert function will add a first and last name record into the database while the select function will find records by last name.  Basic, but I hope you get the idea.

Something to note about my controller though.  I am not doing these database calls from inside an onDeviceReady() function.  Had these functions been fired when the controller loads, they probably would have failed.  Since I am basing the database activity off button clicks, it is probably safe to assume the device and database is ready for use.

If you wish to delete any of your SQLite databases you can do so by including the following:

There are plenty of other ngCordova and baseline SQLite commands that you can make use of.  The plugin documentation is very thorough and worth a read.  If you want to use this SQLite plugin in Ionic 2, you should check out my tutorial on the subject.

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.

  • Rogerio Alencar

    Success! Got it!

    I did not put the var db = null ..
    maybe that was the problem ..

    Thank you.

    • Awesome! I’m glad it worked out 🙂

  • Wiki

    Helpful, Thank you buddy 🙂
    shall i use $ionicPlatform.ready function for each controller?

    • That should be fine.

      If you plan to not automate this process on controller attach, you can get away with what I did since the plugin will probably be ready by that time.

      Regards,

      • Wiki

        Great, Thank you ::)

  • Mendez

    Hello Nic, I’m a noob on the ionic and angularjs and I d like know if you could post a project with sqliten on the github for us run ?

    tks

    • Hi Mendez,

      I will work on creating a YouTube video with step by step instructions for using SQLite in your project.

      Regards,

  • jargalbaatar

    Not work. ngCordova module error

    • Are you using a custom version of ngCordova? I recommend you use the full minified version. Make sure that you include it in your HTML before this line:

      If it still doesn’t work, please provide the adb logcat results.

      Regards,

  • kokimomo

    Great, thanks for this awesome tutorial 🙂
    I just have a question, how do I store the .db file in a custom destination ? and how can i export it ?

    • I believe this plugin will only read from the devices protected storage area. Here is a post that might work for exporting it:

      https://groups.google.com/forum/m/#!topic/Cordova-SQLitePlugin/udnL9ttgBzs

      You might try using the Apache Cordova file plugin as recommended in the above link. Find the db file in the protected storage and transfer it to the SD card.

      Regards,

      • kokimomo

        Thank you, gonna try it 🙂

  • DaniloOliveira28

    Nic, thanks for sharing your knowledge! you rock!

    • No problem buddy. Don’t forget to subscribe 🙂

  • Craig

    Hi Nic,

    Awesome tutorial! I have one problem though, Your app has the run and controllers on the same page.. How do we access the db variable when our controller has it’s own page?

    Thanks

    • It shouldn’t change because it is still JavaScript. The run will always execute before the controllers regardless if they are on the same page or not. Just make sure your database variable is global to all JavaScript.

      Please show me a Gist on GitHub if we’re not talking about the same thing. 🙂

      Regards,

      • Craig

        Ah right, how strange. When I try run some insert code from a button, it give me the “Error: null is not an object (evaluating ‘n.transaction’)”.

        This was done on the emulator and viewing the code using Safari.

        Any ideas what could be the problem?

        • Rule of thumb, don’t test plugins in a web browser. They usually only work on device or simulator.

          With that said, can you confirm your database variable is not null before doing an execute?

          Regards,

          • Craig

            It doesn’t seem to find the global variable on my controller 🙁

            You can see the test code here:

            https://github.com/tutchmedia/TestApp

            Thanks

          • So I looked at your code and I think your problem is that you have two run methods attached to your app.js module. I don’t think the run method that contains your database code is being executed, but instead the other run method.

            I indirectly tried your code by creating a new project of my own. It uses an app.js and controllers.js file. The SQLite code works without error.

            Please fix your double run method and let me know if that resolves the problem.

            Regards,

          • Craig

            Turns out you were correct 🙂 It was a massive issue with the 2 together.

            Very big thank you for the help 😀

          • No problem! Don’t forget to subscribe 🙂

  • Debal

    Hello,
    thank you for this tutorial. I have a question though : I haven’t installed this cordova plugin but I’m still able to use SQLite on Android & iOS using this kind of native JS process : http://www.tutorialspoint.com/html5/html5_web_sql.htm
    What is the plugin helping at ?
    Thank you

    • The Apache Cordova plugin uses native SQLite where as the tutorial you linked uses Web SQL. The plugin creator made a wrapper for the native SQLite to mimic the Web SQL API to give users a familiar interface.

      Native SQLite, as done with the BrodySoft plugin, will always outperform what JavaScript has to offer.

      I hope this makes sense 🙂

      Regards,

      • Debal

        Got it. Thanks for clarifying 🙂

  • Thanks for an excellent tutorial Nic. Very helpful and clear. I am working on an Ionic project now and trying to use the SQLite plugin, but I think I am running into a race condition as far as Angular JS showing the first screen and the database results coming back from SQLite. I have set up the initialisation code within the $ionicPlatform.ready() block as you have in app.js.

    I have set up a factory function getCount() to return “SELECT COUNT(*)…” from my database, and in my controller.js, I have set up some initialisation code like: $scope.myVar = MyService.getCount(); under the main screen controller.

    Problem is when my app loads, the first screen which has a placeholder {{ myVar }} comes up with exactly that – the text “{{ myVar }}” on the screen instead of the evaluated expression. If I leave the first screen and come back to it later via normal navigation, the expression seems to evaluate Ok. I think it is all a ‘timing’ issue, and I think I may have to change the timing or use $timeout() somewhere to keep things in proper order. Looking at the logs currently, it appears that MyService.getCount(); etc. is called AFTER the first screen loads up.

    • Hi Devan,

      What do the logs say when {{ myVar }} displays on the screen? There should be an error of some sort, which may or may not indicate a timing issue.

      Let me know and we’ll start there.

      Regards,

      • Nic – thanks for that, but I solved the issue. I just hadn’t wrapped my SQL statements in a proper Promise fashion, so the functions were returning while the SQLite requests were still busy. Lots of nulls everywhere causing AngularJS to have a fit and interrupt the screen rendering. Once I sorted out all the proper .then() promises, everything started to tick along nicely. Thanks for your offer of help.

        This may be actually an idea for another blog post for you – explaining how javascript Promise works in Angular, as a better alternative to callbacks (if you haven’t already done so). 🙂

        • I’m glad you got it working. Thanks for following up!

          I will see about an AngularJS promise tutorial 🙂

  • Muhammad Rossid Noor Ichsan

    excuse me sir,i am a newbie cordova user , iam interesting to try this one but i dont know how can i start from ? can i see the tutorial video or something about this . i hope you can help me as soon as possible

    • Hi Muhammad,

      Most of my Apache Cordova / Ionic Framework tutorials include videos and ALL of my tutorials show you how to make an application from scratch, including this one.

      I suggest you browse my blog archive and view the tutorials that meet your needs.

      Regards,

      • Muhammad Rossid Noor Ichsan

        ok i’ll see it soon

        about this video toturial,i was try in my genimotion but its give me error like this ,
        i guess it was an error from my genimotion,could i know what a virtual device that you used in geny
        thanks

        • I use a Nexus 4 with Android 4.4.4 for all my video tutorials.

          I am unfamiliar with that error though. You may want to ask about it in the Ionic Framework forums.

          Regards,

          • Muhammad Rossid Noor Ichsan

            thanks before, i was finished that problem,but i have a new prolem now,
            i was following your video toturial as what you say but now i have a new problem “TypeError: n.sqlitePlugin is undefined” can you fixed it?
            please i dont know how to fixed it ,,

            as we know you just do that perfectly completed but i have an error like this after i follow your toturial video

          • This is very vague, so I’m going to ask a few questions that will help for troubleshooting:

            1. Have you installed the Cordova SQLite plugin?
            2. Do you have ng-cordova.min.js included before the cordova.js file?
            3. Are you trying to access the plugin before it is loaded? For example, outside an $ionicPlatform.ready() or onDeviceReady() method.
            4. Is this error happening in one of your controllers or the module.run method?

            The more information you provide, the better.

            Regards,

  • You always save my life lol.
    This is a perfect portal for a newbie like me in cordova.

    • No problem! Glad you like my articles 🙂

  • Hariprasad

    Thank you very much…
    I m struck in db before watching the video…

  • Mark Jagunap

    Hi Nic. The tutorial is very helpful, however I got stuck in the problem on how will i be able to display the data result to the view. I’m a bit new with sqlite and in $http you just directly attach the result to the scope like so $scope.todo = result; when I tried it using sqlite all i get was a blank page and no error whatsover on the console.

    • Hi Mark,

      SQLite returns an object that cannot be directly used on your $scope like that. You must first translate it. See the following post on the Ionic Framework forum:

      http://forum.ionicframework.com/t/sqlite-integration/14136/6?u=nicraboy

      Let me know if you have further questions.

      Regards,

      • Mark Jagunap

        Hi Nic,

        Thanks for the reply. I already tried to do that but still got a blank screen. Here is the script and let me know where i got it wrong.

        $scope.home = {};

        $scope.home.contractor = [];

        var fetchAll = function (result) {
        var output = [];
        for (var i = 0; i < result.rows.length; i++) {
        output.push(result.rows.item(i));
        }
        return output;
        };

        var SQLquery = "SELECT contractor FROM contractor_info";
        $cordovaSQLite.execute(db, SQLquery).then(function(res) {
        $scope.home.contractor = fetchAll(res);
        }, function (err) {
        console.log('Error: ' + err);
        });

        Do i need to JSON.stringify it after converting it to array?

        Regards.

        • At first glance it looks correct.

          Are you sure your query is returning data? Print the results to the console like I did in my guide. If it truly has data, then you should be getting an error in your logs.

          Just to confirm, you’re running from the device, not web browser. Correct?

          Regards,

          • Mark Jagunap

            Yes, I’m running it using adb over network and then the console, just like what you are doing in your video. When i do console.log(result.rows.item(0).contractor); it returned and showed the value corresponding the index on the console. However, when i run it with the script i posted i’m not getting any data even on the console.

          • Mark Jagunap

            I finally got it to work. A typo on the list layout. Thank you for pointing out the difference in getting the data result from sqlite. It took me whole day scratching my head looking at different search engine results and I bet a lot of people are asking it also but no one bother to answer it or point out the difference. Or maybe i was looking at the wrong web pages. Again, thank you very much. I think I can sleep soundly now. 🙂

          • Awesome! Glad you figured it out. Typos are always the worst. Happens to the best of us 🙂

  • AndiSun

    Hi!
    Please help.
    What to do and where to put existing sqlite db file?
    I’ve put it to myProj/www/bd/my.db and try
    db = $cordovaSQLite.openDB({ name: “bd/my.db” });
    but no any results
    How to connect to my.db file if base exist?

    • The db file must be in the protected partition of the device. It cannot reside in the application bundle like other assets. You must first copy the database file from your www/bd/my.db directory to your installed app directory. Then you should be able to access it.

      https://github.com/an-rahulpandey/cordova-plugin-dbcopy

      I have not personally tried the above plugin, but it looks like it should work.

      Regards,

      • AndiSun

        I am tring to use this plugin:
        1) in browser (after ionic serve) I see error:

        TypeError: window.plugins is undefined
        window.plugins.sqlDB.copy(“est-lite.db”,copysuccess,copyerror);

        1) in android device:

        window.plugins.sqlDB.copy(“my.db”,copysuccess,copyerror);
        Works without errors
        but I can’t see any tables in my.db and I think file only created and base empty
        Any ideas?

        • As a general rule of thumb, don’t try to test Apache Cordova plugins in the browser. They often wont work.

          Like I said previously, I haven’t used the DB copy plugin. It was the first one that came up in my Google search. For checking if files exist you may want to check out the Cordova file plugin. You may also want to contact the developer of the DB copy plugin if that’s what you’d like to use.

          Regards,

  • James

    Thanks for the tutorial – very much appreciated. One question; is it possible to view the created database? I know its created per device, but it would make things alot easier to debug if I could view the DB.

    • Hi James,

      For Android, the database resides in protected space so you have two options for viewing:

      1. Try this plugin that I found on Google to copy the database outside of protected space. https://github.com/an-rahulpandey/cordova-plugin-dbcopy

      2. Root your device and install a SQLite viewing application so that the protected space can be viewed

      This Cordova plugin is based on the WebSQL API, so with some tinkering you could also configure it to be tested in your browser.

      Regards,

      • James

        Great, thanks for the help

  • Hariprasad

    I cant access github in India Its blocked
    Any other way to get cordova sqliteplugin

    • I really don’t know.

      As someone who writes libraries, I wouldn’t upload to more than one location. I can’t imagine others will either.

      Sorry,

      • Hariprasad

        Its K,I got it from a proxy site

  • Hariprasad

    Hi just followed your code

    But i got this error.

    SQLitePlugin openargs: {“name”:{“name”:”mydemo”},”bgType”:0}

    ionic.bundle.js:17696 TypeError: undefined is not a function

    at SQLitePlugin.open (http://localhost:8100/js/SQLitePlugin.js:112:15)

    at new SQLitePlugin (http://localhost:8100/js/SQLitePlugin.js:54:10)

    at Object. (http://localhost:8100/js/SQLitePlugin.js:425:14)

    at Object.argsArray [as openDatabase] (http://localhost:8100/js/SQLitePlugin.js:30:20)

    at Object.openDB (http://localhost:8100/js/ng-cordova.min.js:2:31424)

    at new (http://localhost:8100/js/controllers.js:11:24)

    at invoke (http://localhost:8100/lib/ionic/js/ionic.bundle.js:11591:17)

    at Object.instantiate (http://localhost:8100/lib/ionic/js/ionic.bundle.js:11602:23)

    at $get (http://localhost:8100/lib/ionic/js/ionic.bundle.js:14906:28)

    at updateView (http://localhost:8100/lib/ionic/js/ionic.bundle.js:42986:30)

    Here is my code…

    var mydb = null;

    angular.module(‘starter’, [‘ionic’, ‘starter.controllers’, ‘starter.services’,’ngCordova’])

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

    $ionicPlatform.ready(function() {

    if(window.cordova && window.cordova.plugins.Keyboard) {

    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

    }

    if(window.StatusBar) {

    StatusBar.styleDefault();

    }

    mydb = $cordovaSQLite.openDB({ name: “my.demo” });

    $cordovaSQLite.execute(mydb, “CREATE TABLE IF NOT EXISTS task (id integer primary key autoincrement, name text, price text,duration text,category text,locname text,location text,parenttask text,foreign key(parenttask) references task(id) on cascade delete)”);

    });

    })

    • Please use Gist on GitHub for posting code. The comments section of a blog is never a good choice due to lack of formatting.

      Two things I’d like you to do:

      1. Remove the SQLite plugin from Cordova and re-install it. Sometimes plugins get corrupted and need to be re-installed.

      2. Build and install the application. I see localhost:8100 in your logs which tells me you are trying to serve this application. No matter what people tell you, the only correct way to test a mobile application is to build and install it.

      https://www.thepolyglotdeveloper.com/2014/12/debugging-android-source-code-adb/

      Let me know the results of both those two requests.

      Regards,

  • Dhaval Kumar

    Hi Nic

    Thanks for the tutorial – very much appreciated

    I have 1 issue in below code
    var db = $cordovaSQLite.openDB({ name: “myDB.db” });

    i’m using “ionic serve” for run project in browser.

    error:
    Uncaught TypeError: Cannot read property ‘openDatabase’ of undefinedng-cordova.js:5058
    openDBapp.js:27
    (anonymous function)ionic.bundle.js:37388
    (anonymous function)ionic.bundle.js:2241
    onPlatformReadyionic.bundle.js:2220
    onWindowLoad

    Could you please help me.

    Thanks,
    Dhaval

    • This is a plugin for devices and should not be tested in a browser or with the ionic serve command.

      Build for Android or iOS and install, then the problem should go away.

      Regards,

      • Dhaval Kumar

        Thanks for instant reply or Help.

        My this big query is now cleared.

        Any other way for test in to browser with the ‘ionic server'(under development process) because it would be very helpful for development process.

        Thanks again 🙂

  • talhaakkaya

    Hi Nic thanks for the tutorial i have one issue

    my app.js like this https://gist.github.com/talhaakkaya/3cda02c8dcae7aef0f86

    but when i run it gives this error

    TypeError: Cannot read property ‘transaction’ of null

    • Can you try to re-add the Cordova plugin and clean your project? I’m thinking the plugin got corrupted, which tends to happen frequently for some reason in Cordova development.

  • thanks for sharing Nic 🙂

  • Emil Rasmussen

    First of all, it’s a great blog and YouTube channel you have!

    Now, my problem.
    When I try adb -r
    platforms/android/ant-build/CordovaApp-debug.apk, I get the following:
    5072 KB/s (348…..)
    pkg: /data/local/tmp/CordovaApp-debug.apk
    Success
    rm failed for -f, No such file or directory

    Then I type in:
    adb logcat, and my console prints a lot of different things,
    and I cannot find “SELECTED -> ….” and “INSERT ID -> …”.

    Do you have any idea, why this happens?

    • It sounds like your install command is incorrect:

      You want the following:

      adb install -r platforms/android/ant-build/CordovaApp-debug.apk

      You were missing the ‘install’ part of the command. When installed, look for ‘SELECTED -> …..’ after opening the application.

      Let me know how that goes for you.

      Regards,

      • Emil Rasmussen

        Hi thanks for the quick answer!

        I forgot to write “install” in my message – I remembered it, when I tried it out in the console.
        Unfortunately, it didn’t work.

        Regards,

        • A few questions:

          1. Windows, Linux, or Mac?
          2. When you run the install command, is your Terminal / command prompts current working directory, the root of your project?
          3. Device or simulator?
          4. Are there any exceptions or stack traces in your ADB logs after launching the application?
          5. Have you ever gotten a Cordova / Phonegap / Ionic app working, or do they all fail like this?

          Should help put us on the right track.

          Regards,

          • Emil Rasmussen

            1. Windows
            2. The current working directory is in C:……myApp
            3. Samsung Galaxy S3
            4. I’m not quite sure. But there comes exceptions.
            5. The apps work without any problem.

            Regards,

          • Can you copy and paste the logs after you open the application?

            I’d like to have a look.

          • Emil Rasmussen

            Yes, I can do that, but there come a lot of logs afterwards.
            Should I still post it in the next reply?

            Regards,

          • Go for it! If it is too much I can just delete the comment. Just make sure it is everything from the moment you hit the open button for the app. Nothing before.

          • Emil Rasmussen

            Okay, cool.
            I’m from Denmark, which means that right now it’s 01:41 AM,
            so I’m going to sleep. I will post it tomorrow.

            Thanks for everything so far!

          • Emil Rasmussen

            Okay, first I just found this, when I ran the application (ionic run android).
            Using apk: C:…….platformsandroidant-buildCordovaApp-debug.apk.

          • Emil Rasmussen

            There are hundreds of lines, so it was kind of hard to get everything, but I have these two screenshots. Forget the first screenshot here because I just found out that I got a SMS…

          • The second screenshot has exactly what I needed.

            Although not easily readable, there is a percent encoded error message saying that you did not properly include the ngCordova library into your project.

            Please check to make sure you included it above the cordova.js line in your index.html file and also included the module directive in your app.js file. Let me know when you can confirm this.

            Regards,

          • Emil Rasmussen

            I found out that I had forgot to set the extension .js,
            but it didn’t work anyway.

            My index.html:

            So there shouldn’t be any problem. I chose js/ng-cordova.js myself,
            but that isn’t a problem, is it?

            Regards,

          • What is the new error?

          • Emil Rasmussen

            It looks like kind of the same.
            It’s mostly ionic.bundle.js, it’s complaining about.

          • Please share your project on GitHub. I think that is the best next step.

            Regards,

          • Emil Rasmussen

            Here you are. Again, thanks for helping me out!
            https://github.com/fit-etar/sqlite-issues

            Regards,

          • You have a typo in your index.html file. The script tag for ng-cordova is missing a letter.

            You may want to read this:

            http://ionicframework.com/blog/minifying-your-source-code/

          • Emil Rasmussen

            Wow, that’s nice.
            I still have the problem with rm failed for -f, No such file or directory,
            but when I hit “Insert”, then it prints “INSERT ID -> undefined:38”.
            Now when I hit select, then I get that there is an error. I will try to fix that. It’s something that is on line 58 in my app.js.

          • Emil Rasmussen

            I can give you two screenshots of when I hit “Select” and then “Insert”.

            It looks promising, but it doesn’t work entirely.

          • Emil Rasmussen

            It finally worked, when I copy/pasted your code. Now I have to change it to “my” code.

            However, when I type adb -r install …., then I still get the error.
            But! It works, when I hit “Select” or “Insert”.

            THANK YOU, VERY MUCH!

            Regards,

          • I’m glad it worked!

            The error might be a configuration issue with your Cordova, but I’m not sure.

            And you’re not bothering me. I’m happy to help.

          • The screenshots you provide are not too helpful because you miss more than half of the actual error. I’d much prefer you to copy and paste the error logs if you feel the need to share.

            I think your problem is on this line:

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

            That is line 48 on your GitHub. You provide a prepared parameter, but your query does not expect one.

            At this point, your code appears to be working. Looks like you just have SQL bugs to fix.

            Regards,

  • Ash

    Hey its a great blog, but I keep getting a “TypeError : Cannot call method tansation of null” do you know what that means… I would be happy to show you my code but its pretty much the same as yours just copy and pasted

    • Can you please confirm with me that you are testing on a device or simulator and not with your web browser?

      Regards,

      • Ash

        Hey, im sorry I sent a much more detailed post on the ionic forum. I tested on a device (Samsung Note II). Here is the post I sent to you via Ionic forum. It has the shows the logcat error.

        I keep getting the message below in my logcat (running on device)

        D/CordovaLog(10294): file:///android_asset/www/lib/ionic/js/ionic.bundle.js: Line 19387 : TypeError: Cannot call method ‘transaction’ of null
        D/CordovaLog(10294): at Object.execute (file:///android_asset/www/js/ng-cordova.min.js:9:15994)
        D/CordovaLog(10294): at Scope.$scope.insert (file:///android_asset/www/js/controllers.js:130:24)
        D/CordovaLog(10294): at $parseFunctionCall (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:20124:18)
        D/CordovaLog(10294): at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:50863:9
        D/CordovaLog(10294): at Scope.$eval (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:22178:28)
        D/CordovaLog(10294): at Scope.$apply (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:22276:23)
        D/CordovaLog(10294): at HTMLButtonElement. (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:50862:13)
        D/CordovaLog(10294): at HTMLButtonElement.eventHandler (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:10823:21)
        D/CordovaLog(10294): at triggerMouseEvent (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2811:7)
        D/CordovaLog(10294): at tapClick (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2800:3)

        I am using your code (copy and pasted) trying to get it to work. Do you have any idea where this error may be coming from. I cannot thank you enough for your blog posts, mighty helpful.

        • I’m wondering if the plugin got corrupted somewhere. It does happen, although no one seems to know why.

          Try removing the SQLite Apache Cordova plugin using the appropriate Terminal command. Then re-add it.

          Let me know if that works. If it doesn’t, put your project on GitHub and I’ll take a look.

          • Ash

            Will do. Thank you for the help.

          • Ash

            Hey Nic,

            Didn’t seem to work. If you have 5 min I uploaded my project to GitHub. The link is below.

            https://github.com/charlesandash/ionicapp

            The app is kind of messy… just open the side menu and click DBTest (view the console when you insert and select exactly like your blog post)

            I know your extremly busy so if you cant look at it, no worries.

          • You originally said you copied and pasted my code, but I can see that is not the case based on the project you uploaded ;-).

            When learning something for the first time you should start small. Follow my tutorial exactly and tell me if it works. Don’t try to integrate it with your own project until you understand the basics.

            I’ll check out your GitHub version tonight or over the weekend.

            Regards,

          • Ash

            So it is the same, everytime I occured a new functionality I was making a new tab (navigation) in this case DBTest. I copied your controller and created two buttons. I can extract it into a new project and remove everything else if that is easier. I did not mean to mislead you in any way. My appologies.

          • Don’t worry about it. Just trying to have you start small and work your way up :-).

            I’ll report back in the next day or so.

          • Your GitHub project worked without issue for me. See the attached screenshot.

            Steps I used:

            1. Download your project
            2. Create a fresh project on my desktop because Git is known to mess up the Ionic project structure
            3. Replace the www folder of the new project with the www folder from your GitHub project
            4. Add the Android platform
            5. Add the SQLite plugin via the instructions of this article
            6. Build and run

            See if you can do the same.

          • Ash

            Thanks Nic. I really appreciate your help.

          • No problem!

          • Ash

            Hey,

            Normally, I would not write this on a public forum however I was unable to find anyway to send you a direct message. Thank you again for your help. After seeing how knowledgeable you are in computer science, I wanted to get your advice regarding the best way to learn HTML, CSS, AngularJS, Ionic, and Hybrid Application development. I graduated from UMiami in cs and chemistry and I have experience with C, Java, and Android. The skills I learned in school were great, however, I have found that its practical application is limited. I plan on going to medical school and bridging the gap between technology and medicine. I wanted to see how you would approach learning web technologies. Your advice would be awesome. Cannot thank you enough.

            Thanks,
            Ash

          • Send me a direct message on Twitter. That would be best @nraboy

          • Ash

            Will do. Can you please accept follow request on twitter

          • What is your Twitter name?

          • Ash

            @sampathash

    • onurn

      Hello,

      I have receiving the same error. Did you find a solution ?

      Thanks

  • Hi Nic, congrats yout tutorial, very good quality!
    I publish similar content, and share here.

    https://github.com/CharlesMendes/ionic-sqlite/

  • Fábio Antunes

    Hey Nic, one question that bothers me is the ionic platform ready, Imagine that I would like to create a factory that wraps my Database logic, with get and insert functions. Some of this functions are called when the Controller is instantiated, so I can’t assume that the plugins will be loaded before the Factory is called by the Controler the request.

    Here’s a JSfiddle with some code.
    http://jsfiddle.net/doh0zywe/

    What’s your suggestion to solve this?

    • Is there anything preventing you from putting $ionicPlatform.ready() in your controller? Make sure the plugin isn’t involved with any of the initialization logic. Then access $cordovaSQLite functions, from within the $ionicPlatform.ready(). Shouldn’t throw any errors until you actually try to use the functions, in which case we’re covered because the plugin will be ready.

      Let me know if that didn’t make sense.

      Regards,

  • Boris Sondagh

    This tutorial helped me a lot, a big live saver, thanks!

    I’ve extended on it with a service wrapper, also containing insert & edit statements and a comment on how to use this with Ionic serve, it’s available here:
    https://gist.github.com/borissondagh/29d1ed19d0df6051c56f

    Hope that helps somebody as well.

    • Awesome, thanks for sharing!

    • disqus_7ar3cRnB4p

      Unfortunately the gist is gone – do you happen to have it somewhere? It would help me a lot. Thank you!

    • Arismel Lyon O’conner

      404

  • java training in chennai

    Hi this is dwarakesh i am having 3 years of experience as a php developer and i am certified. i have knowledge on OOPS concepts in php but dont know indepth. After learning java will be enough to get a good career in IT with good package? and i crossed
    java training in chennai website where someone please help me to identity the syllabus covers everything or not??

    thanks, dwarakesh

  • java training in chennai

    Hi this is dwarakesh i am having 3 years of experience as a php developer and i am certified. i have knowledge on OOPS concepts in php but dont know indepth. After learning java will be enough to get a good career in IT with good package? and i crossed
    java training in Chennai website where someone please help me to identity the syllabus covers everything or not??

    thanks, dwarakesh

  • Albert Vince Mendiola

    Hi Nic!, nice tut. I’ve followed your tutorial but i got this error on my console Uncaught TypeError: Cannot read property ‘openDatabase’ of undefined. i’m emulating it in Google chrome. how should i fix this?

    • This is a native device plugin, so you cannot use a web browser to test. You must test it on a device or simulator.

      You can however, make a very small adjustment so if the device or simulator is not detected, it falls back on WebSQL instead:

      Regards,

      • Albert Vince Mendiola

        Thanks Nic, i will try that.

        Regards,

  • Android Training in Chennai

    Hi this is Kathiresan i am having 3 years of experience as a dot net developer and i am certified. i have knowledge on OOPS concepts in .NET but dont know indepth. After learning android will be enough to get a good career in IT with good package? and i crossed Android Training in Chennai website where someone please help me to identity the syllabus covers everything or not??

    Thanks,
    kathiresan

  • Android Training in Chennai

    Hi this is Kathiresan i am having 3 years of experience as a dot net developer and i am certified. i have knowledge on OOPS concepts in .NET but dont know indepth. After learning android will be enough to get a good career in IT with good package? and i crossed Android Training in Chennai website where someone please help me to identity the syllabus covers everything or not??

    Thanks,
    kathiresan

  • Matt Kraemer

    Great tutorial, thank you. Any chance to get an example or tutorial with a form? I’m still struggling with connecting a form and the database.

    • Thanks!

      I was planning on doing a full app tutorial in the near future. This may be a part of it. Stay updated by subscribing since I don’t have a date yet.

      Regards,

      • Barry Mc Gettigan

        Submitting a form tutorial would be great. Thanks for the demonstrations.

  • Enamul Haque

    Hello Nic Roboy
    Nice Tutorial.Please Publish full part of the tutorial. I am still struggle to connect sqlite database as local storage.

    • SQLite is an alternative to local storage.

      What errors are you getting? Are you testing in a browser, simulator, or on a device?

      Regards,

  • Hi this is Rajesh i am having 3 years of experience as a php developer and i am certified. i have

    knowledge on OOPS concepts in php but dont know indepth. After learning Dot Net will be

    enough to get a good career in IT with good package? and i crossed dot net training in chennai website where

    someone please help me to identity the syllabus covers everything or not??

    thanks,

    Rajesh

  • Hi this is Rajesh i am having 3 years of experience as a php developer and i am certified. i have knowledge on OOPS concepts in php but dont know indepth. After learning Dot Net will be enough to get a good career in IT with good package? and i crossed dot net training in chennai website where someone please help me to identity the syllabus covers everything or not??

    thanks,

    Rajesh

  • My question is the sqlite return is very slow, I have wait always. I have post on stackoverflow. http://stackoverflow.com/questions/28408188/ionic-framework-use-cordova-sqlite-slowly

    • Are you testing on a device or simulator? What is the OS version? What is the size in MB of your SQLite database? How many records are you querying for?

      These are all questions that could relate to slow speed. Once you answer them, we can go from there.

      Regards,

      • Thanks your help. Let me check your question first.

      • Hi, thanks your question. When I testing on ios simulator, it’s work. But why I test it different on the chrome and simulator.

  • Hoang

    Can you upload your project on github. Thank you very much.

    • I don’t put my projects on GitHub because I feel a video and written tutorial is sufficient. If my tutorial doesn’t do the trick I encourage you to ask questions. You’ll learn it better that way.

      Regards

  • Somaraj

    Good Article Nic, this helped me a lot.
    Just one clarification, how can i view the SQLite Database created in the actual android device? do we have any tool?

    • You would have to root your device and install a SQLite browser from the app store.

      SQLite databases are put into protected space so only the app that ships with can read it. This is why root is necessary.

      Regards,

      • Somaraj

        Thanks for the information

  • affiBox Show

    I just want to say that I’ve try following this instructions and it just won’t work… I keep getting a tons of errors. Example. windows.sqlitePlugin is not define

    • Sounds like you’re probably trying to test in a web browser rather than a device or simulator.

      Can you confirm this and paste your logs?

      Regards,

      • affiBox Show

        I did it on android and it crashes the app. And I’m only declaring the db variable.

        I don’t see a way around it.

        Later today I’ll post the logs

        • Put your code on GitHub too

          • affiBox Show

            Got it working… Thanks!!! 😀
            I use monitor.bat to see the errors….

  • SubjectiveEffect

    Hi Nic,

    Nice little API you’ve made there with your insert and select functions. Reminds me of the Ionic one for use with localStorage.

    What would be really great would be a method that degrades gracefully to WebSQL so this can all be tested in the browser. At the moment I’m using this:

    }

    but I’m struggling to build out the app.

    • I have a few posts on this subject queued to publish over the next few weeks. Hang in there.

      Regards,

  • Utpal

    Hi Nic,

    Thanks for this nice tutorial. I was wondering can the SQLite db be pre-populated into the app? Or there is no alternative but to create it onDeviceReady() event.

    Thanks,
    Utpal

  • iJorl

    Hello Nic

    First I really want to thank you for your amazing tutorials, they really help me getting into ioinic …

    I have a question, i tried to make your example app with the SQLite storage on a mac and emulatet it on it and i don’t get it working

    i always get : “ERROR: No such database, you must open it first” when i try to insert or to select elements. but when i first create the DB there are no errors….

    Could you please give me a hint how to solve my problem ?

    Thanks, iJorl

    • Put your project on GitHub and I’ll take a look

      • iJorl

        Thank you very much, here is the link to my github repo:
        https://github.com/iJorl/Ionic-Dev/tree/master/SQLExample

        • Can you share your full logs so I can see what line the error happens on. It could be different than you think.

          Regards,

          • Mohamed Mehrez

            Hi,thanks for your time Nic,i just attached a screenshot of my logs,this all appears when i try to select.

          • No results found is leading me to believe one of your queries is bad. Maybe a typo somewhere.

            Please put your full project on GitHub and I’ll take a look.

            Regards,

          • Mohamed Mehrez
          • In your index.html file your select() function is missing a lastname parameter. This is why your select statement is returning no data because you’re not satisfying your prepared statement with the lastname parameter.

            Regards,

          • Mohamed Mehrez

            Ah you’re right,i’m glad it was as simple as that,thanks Nic,it works!
            i have one question,am i able to store the database online ? if not using this plugin,can you suggest any solution ? i want the same database to be shared with all users in case there are queries that are triggered by users themselves..i hope you understand what i’m trying to say. Thanks!

          • You’ll have to write your own service or use a service that already exists. Examples:

            PouchDB
            Firebase
            Dropbox Datastore

            There are many out there, but if you truly want to use straight SQLite, you’ll probably have to write your own.

            Regards,

          • Mohamed Mehrez

            Thank you so much for your help Nic…i will check them out 🙂

    • John

      Hey there,

      I had the same exact problem. I discovered that ngCordova’s wrapper for the SQLite plugin doesn’t support passing an object as the options argument. To open the database, your code is doing:
      db = $cordovaSQLite.openDB({ name: “my.db” });

      The ngCordova wrapper only supports calling openDB with two arguments for the name and background values, like this:
      db = $cordovaSQLite.openDB(‘db name’, ‘background type’);

      If you change your code to this, it should work:
      db = $cordovaSQLite.openDB(‘my.db’);

      • Thanks for pointing this out. I think the command changed recently in ngCordova and I hadn’t seen it yet. The joys of working with a tool that is in alpha testing (ngCordova).

        I’ll update the tutorial soon to reflect.

        Regards,

        • John

          No, thank you! I was absolutely lost about how to get started with the Cordova SQLite stuff until I stumbled upon your blog post. Also really glad that the ngCordova plugin exists, it makes everything so much easier!

      • iJorl

        Thanks for your comment, now everything works just fine : D

  • iGeo

    Thanks for sharing. I just change my connection like these:

    self.db = window.openDatabase(“mydb”, “1.0”, “myApp”, -1); //Browser
    self.db = window.sqlitePlugin.openDatabase(“mydb”, “1.0”, “myApp”, -1); //Production

    and it’s working. Thanks! ^_^

    • No problem. I’m glad you got it working!

  • Marvin Sanchez

    Hi, thank you a lot for this tutorial it’s very helpful. But how can I get res.row… inside a variable? Because even if the variable is global like db, I can’t access it from the cordovaSQLite function

    • Inside the callback you can store it inside a $scope variable. Does this answer your question? If not, please give me more information such as logs or code that you’ve tried.

      Regards,

  • jackson

    Thanks for sharing this informative blog..If anyone want to get Salesforce Training in Chennai reach FITA academy.

  • jackson

    Your posts is really helpful for me.Thanks for your wonderful post.It is really very helpful for us and I have gathered some important information from this blog.If anyone wants to get Dot Net Training in Chennai reach FITA, rated as No.1 Dot Net Training Institutes in Chennai.

  • steve

    Hi Nic,
    I have a question, can you explain for me. I’m following your tutorial with sqlite. I create a factory for AppDB like this, in different file services.js. And i declare var db = null in app.js file.

    .factory(‘AppDB’, function($cordovaSQLite, $localStorage){
    var table = “statement create table”;
    return {
    initDB:function(){
    db = $cordovaSQLite.openDB(“test.db”);
    $cordovaSQLite.execute(db, table);
    console.log(“Create database successfully”);
    },
    loadData:function(sms){
    // execute some query db
    }

    In initDB function, db create successfully, but when i call loadData method, i recheck and db null. So can you explain for me why is it. I got in stuck with this issue

    • You might want to use an AngularJS service or rethink your AngularJS factory. If you created a service you could initialize your database in it so that way it is global to the other functions and methods of the service.

      • steve

        Oh tks for your help Nic. I’ll try your way and notify you soon the result.
        Thanks again.

      • steve

        Hi Nic,
        Thanks for your help very much. I change from provider to service and it works.LOL. It took me a lot of time.

        • Hey, I’m glad that you got it working. Learning takes time, but at least now you probably won’t make the same mistake twice 🙂

  • kameshtagore

    Hi Nic,

    Thanks for the amazing tutorial. I have been trying to figure out a solution for a SQLite issue for quite sometime. Could you please help me to solve the problem?

    Mine is an android app that backup its SQLite DB periodically in the cloud. My requirement is when an user installs the app in a second device and connect to the cloud, the sqlite DB should be imported instead of the app creating a new one. But Cordova SQLite plugin expects the pre-populated db to be in the www folder to import (https://github.com/brodysoft/Cordova-SQLitePlugin#pre-populated-database).

    So my question is, how to use/import a pre-populated database in my app which is not available under www folder.

    Thanks in advance, Kamesh.

    • This tutorial I made might help you:

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

      It will transfer the SQLite DB into device protected space and then the brodysoft plugin will be able to read it.

      Regards,

      • kameshtagore

        My understanding is that the SQLite DB should be in the www folder for bcopy plugin to work. How can I copy the file from an external url to the www directory after the apk is installed? I guess the downloads directory or any temp directory would be a best choice to keep the downloaded db.

        Regards,
        Kamesh

        • You’re right! I don’t know what I was thinking.

          Instead of copying the database to your server you’ll need to work with SQL scripts. You should probably craft a factory for exporting data to a SQL file as well as loading it.

          However, SQLite is probably not your best choice for data synchronization across devices. There are so many other superior solutions to this such as Firebase, PouchDB, or Parse.

          Regards,

  • hhh

    fgfgfg

  • hhh

    thryuuu

  • suranka
  • Mohamed Mehrez

    Hi Nic,great article.

    i’m getting this error
    Uncaught TypeError: Cannot read property ‘openDatabase’ of undefined ng-cordova.min.js:10

    • Are you testing from a device or simulator? This tutorial does not work in a web browser or using ionic serve.

      Regards,

      • Mohamed Mehrez

        Hi,
        you are right,i just tested on my phone and it works,however,reading from the database does not work for some reason,inserting works like charm tho.i did verify my code and it looks exactly like yours,i’m quiet sure i didn’t miss any step. hope you can help. Thanks.

        • What do your logs say? Without seeing the logs, I won’t be able to help you further.

          Regards,

  • Thanks for this. Do you know the storage limit? I am trying to save base64 images and considering SQLite- if it allows for big storage.

    • If you’re using the plugin, I don’t believe there is a limit because it uses native device SQLite. However, if you’re using WebSQL (browser SQLite), I think the limit is 5MB.

      So using this tutorial, you should be fine.

      Note, I’ve heard rumors of Apple rejecting apps that ship with databases that are too large. So make sure it starts small when you ship it 🙂

      Regards,

  • Hello Nic, is it possible to test the sqlite storage in a webview somehow?

  • Hey Nic. Read about this: http://www.brentengwall.com/websql-and-sqlite-with-ionic/

    Just found it, basically if you are testing it in Chrome, then it outlines how to deal with it. (Solves the problem of OpenDatabase not found).

  • Hi, I did everything as in the tutorial (copy/pase), but when I start my Ionic App on my device, then nothing happens… also the view in which I insert the member seems not to execute (you see the variables in brackets like {{name}}. What is going on?. To clarify, I included also window.alert(“hello I am inside run) inside the .run of the app.js (after the {} if window.statusbar), but that also does not trigger…

    Btw, In my config.xml (as I deploy my app through Phonegap build) I also included the plugin ()

    • That is probably your problem. I can’t say I recommend using Phonegap build or any other cloud building solution. They tend to not work as expected.

      I recommend installing the appropriate SDKs on your machine and building locally. You’ll get much better results.

      Regards,

      • Perhaps something to do with Safari? In Chrome it works perfectly fine, but on Safari not…

        • I generally don’t test in Chrome or Safari, but when I do, I usually test in Safari. But I’m on a Mac, so I don’t know if that makes a difference.

          You should make it a habit to only test on a device or simulator, regardless on how inconvenient it might be.

          Regards,

  • Yas

    Hi Nic,

    When I try an ‘Insert into’ statement with a TEXT value, only the first 4046 bytes of the text is added.

    I understand that the maximum size of a TEXT Datatype in SqLite is reached.

    If it’s the case, what can I do to solve this problem?

  • Nyasha Kapfumvuti

    Firstly, thanks for the great tutorials. I’ve learned a lot in a short space of time. I just have one question: In this example, we loaded our data at the selectAll() event. I’d prefer to do this using the $ionicPlatform.ready event but I cannot seem to get the data to load. Do you have any advice on a suitable approach? Thanks again.

  • Sercan

    thank you nice very beautiful summarize 🙂

  • Jaya Prakash

    @nic i followed your tutorial still i m unable to success. in browser it is working fine, but in device it is not creating database. can you guide me how to fix and test…

    • Read this for testing:

      https://www.thepolyglotdeveloper.com/2014/12/debugging-android-source-code-adb/

      If you tell me the error logs, I can better help you.

      Regards,

      • Jaya Prakash

        this is my app.js

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

        .run(function($ionicPlatform,$cordovaSQLite) {
        $ionicPlatform.ready(function() {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if (window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        }
        if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
        }

        if (window.cordova) {
        db = window.sqlitePlugin.openDatabase({ name: “iautocount.db”, location: 1 }); //device
        }else{
        db = window.openDatabase(“iautocount.db”, ‘1’, ‘auto’, 1024 * 1024 * 100); // browser

        }

        });
        })

        and this is my controller.js

        .controller(‘SettingsCtrl’, function($scope, $http,$ionicLoading,$cordovaSQLite) {

        var que = “SELECT profiledata FROM profile” ;
        $cordovaSQLite.execute(db, que, []).then(function(res) {
        if(res.rows.length > 0) {
        $scope.profdata=res.rows.item(0).profiledata;
        //window.alert($scope.profdata)
        }
        });

        })

        • I’m looking for your logs, not your code. I think you’ll benefit the best from my help if we go through the correct troubleshooting steps together, starting with logs.

          Regards,

          • Jaya Prakash

            Hi Nic,
            i did adb logcat so in command prompt showing this, running continuously without stop. have a look…

          • Jaya Prakash

            if i do ionic run android -lc below logs are showing… i m attaching screenshot.

          • Your first problem is using live reload and or ionic serve. Since those are still beta, I strongly advise you do not use those. I suggest you build a binary APK and install it to your device or simulator. A lot of your problems will disappear after that.

            Regards,

          • Jaya Prakash

            Hi can you guide me how to do binary apk and test.. i m trying to install cordova sqlite from last 2 weeks and still not get solution in device. in ionic serve all working…

          • Build your APK with ionic build android and then install it to your device or simulator with adb install -r platforms/android/ant-build/APKNAME-debug.apk. Then view the logs like so:

            https://www.thepolyglotdeveloper.com/2014/12/debugging-android-source-code-adb/

            Regards,

          • Jaya Prakash

            rm failed for -f,ready-only file system this is the error showing in dos window

          • You lost me. When do you get this error? It sounds like your Android SDK and / or Apache Cordova software is not installed and configured correctly.

          • Jaya Prakash

            HI, ionic run android is working for me. and ionic serve is working for me also apk i install in bluestacks and mobile it is working. so i think android sdk and or apache cordova software is working…
            i m really tensed for sqlite it taken me more then 15 days still now i m not get solution please help me and give me a solution…

          • Might be best for you at this point to put your project on GitHub.

          • Jaya Prakash

            i try github unable to upload files there. can you give me your email or so i will send zip files, or in github how to upload… very difficult process..

          • Sorry, I don’t distribute my email. I’ll only look at code on GitHub.

            Regards,

          • Jaya Prakash

            Hi Nic, sorry for late response. after al i sucess to upload in github

            https://github.com/jswebtech/iautocount

            can u please check now, i m unable to create db in device.
            in ionic serve it is working.

          • You have a lot more in your project than what I’ve included in my tutorial. I think you are attempting to do too much while trying to learn and troubleshoot a problem.

            In your index.html file you have the following:

            That will probably cause all kinds of naming conflicts. I’d choose one of those, not both.

            I didn’t look at your whole project. Please follow my tutorial exactly and let me know the results. When you get my version working, then try to integrate it into yours.

            Regards,

          • Jaya Prakash

            HI, i added in app.js create db and in settingctrol i m inserting data… like your tutorial.

          • Jaya Prakash

            HI Nic,

            i m still unable to create db in device. i did simple ionic start test tabs
            and install cordova sqlite plugin, same problem coming working in ionic serve and not working in device.

          • I encourage you to not use ionic serve, ionic view, and ionic live-reload. They are known to have issues when it comes to plugins.

            Also, please follow my tutorial exactly with a blank project before you try to take it to the next level with tabs.

            Regards,

          • Jaya Prakash

            Hi NIc, thanks i followed exactly your tutorial and success. but i m unable to find database location in device. also you are doing insert and select in button click i want to write that in conroller so with out click it will insert. pls suggest.

          • The database gets created in protected memory. It will not be in the SD partition of the device.

            If you’re going to let the database calls reside in a controller, then you need to wrap them in an $ionicPlatform.ready or onDeviceReady function.

            Regards,

  • I
    agree with your post. Android software development kit makes the application
    development process lot simpler and effective.

    http://www.fita.in/android-training-in-chennai/

  • Kingsley Simon

    I get this error when i run the code and the buttons do not work .

    E/eglCodecCommon( 2508): glUtilsParamSize: unknow param 0x00000bd0
    E/eglCodecCommon( 2508): **** ERROR unknown type 0x0 (glSizeof,72)
    E/eglCodecCommon( 2508): **** ERROR unknown type 0x0 (glSizeof,72)
    E/eglCodecCommon( 2508): glUtilsParamSize: unknow param 0x00000b44
    E/eglCodecCommon( 2508): glUtilsParamSize: unknow param 0x00000bd0
    E/eglCodecCommon( 2508): **** ERROR unknown type 0x0 (glSizeof,72)
    E/eglCodecCommon( 2508): **** ERROR unknown type 0x0 (glSizeof,72)
    E/eglCodecCommon( 2508): glUtilsParamSize: unknow param 0x00000b44
    E/eglCodecCommon( 2508): glUtilsParamSize: unknow param 0x00000bd0
    E/eglCodecCommon( 2508): **** ERROR unknown type 0x0 (glSizeof,72)
    E/eglCodecCommon( 2508): **** ERROR unknown type 0x0 (glSizeof,72)
    E/eglCodecCommon( 2508): glUtilsParamSize: unknow param 0x00000b44
    E/eglCodecCommon( 2508): glUtilsParamSize: unknow param 0x00000bd0
    E/eglCodecCommon( 2508): **** ERROR unknown type 0x0 (glSizeof,72)
    D/TaskPersister( 1219): removeObsoleteFile: deleting file=117_task.xml

    Any help on this?

    • These are not errors related to SQLite or Apache Cordova. My bet is there are other errors somewhere in your log. Can you find others?

  • wendy kurniyanto

    Hi Nic,

    I tried you code and still got en error
    “Error: null is not an object (evaluating ‘n.transaction’)”
    i tried in IOS Simulator.

    could you please help me?
    Thanks.

    • What line is the error and does it happen when you try to insert or select?

      • wendy kurniyanto

        Thanks for your reply Nic.

        Yep it happen when insert and select function.
        I got an error on line 28 and 37. I guest the application doesn’t execute run function (Line 18-19), since the db variable always null.

        Yesterday, I added this code (below) before $cordovaSQLite.Execute and it works fine.
        if (!db) {
        db = $cordovaSQLite.openDB(“my.db”);
        $cordovaSQLite.execute(db, “CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)”);
        }

        but the question is, Is it Ok if i’m doing this?

        Thanks.

        • If you do that, your database is never going to run because it will always be null. So I can’t say I recommend that.

          Can you do a console.log after the $cordovaSQLite.openDB to see if db is null still?

          Regards,

        • Bhavu Patel

          Hello,

          I had the same issue while working on iOS simulator and found that its the security error as database size requested was more then 5MB.

          Before:
          db = window.openDatabase({ name: “eCards.db” }, ‘1’, ‘DBNAME’, 1024 * 1024 * 100);

          After:
          db = window.openDatabase({ name: “eCards.db” }, ‘1’, ‘DBNAME’, 1024 * 1024 * 4); //~4MB~

          Hope this helps.

          Thanks,

  • Saurabh Rajput

    Hello Nic,

    Great tutorials!!

    I am trying to implement what you have described here but still unsuccessful after spending a whole day.

    I am a beginner at ionic and android development. Can you please take a look and suggest whats wrong with the code?

    Problem statement: I am trying to implement a simple note-making app that allows user to take a text note and store it. I have tried this on both the browser and the actual android device(not emulator) but it does not work either way.

    following are the code snippets:

    app.js:

    var db = null;

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

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

    })

    code for controller:

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

    })

    the call to write inot the db is made on the click of a button and the code for that part is:

    take a look at the logcat error: it says cannot call method ‘transaction’ of null:
    same error on browser too.
    I read on a lot of posts that the method openDb() is asynchronous and the variable db is not defined before it is being called. Then what exactly is the solution for this? I have tried waiting for 10 mins before pressing the save button but that too does not work.
    Please help!

    • Please put your code on GitHub. It is too complicated to look at in the comments.

      Regards,

  • Munkh-Orgil Myagmarsuren

    Hi it works fine but where my.db created, Can i use my own db instead of my.db ???

  • thanks

  • Thanx for sharing

  • Its odd.
    I’ve got error message on browser console:”Uncaught ReferenceError: $cordovaSQLite is not defined” on app.js. Its my script for app.js:

    “var db = null;

    angular.module(‘myapp’, [‘ionic’, ‘myapp.controllers’, ‘myapp.services’, ‘ngCordova’])

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

    $ionicPlatform.ready(function() {

    });

    })”

    How I can fix it?

  • FITA is the leading dot net training institute in Chennai
    offering dot net course in Chennai. Our
    certified and experienced trainers will help students to learn .net programming
    from the scratch. With our professional training, we train students into
    industry ready professionals.
    http://www.fita.in/dot-net-training-in-chennai/

  • Fagner Gonçalves

    How to sync database from remote server using sqlite?

    • You might take a look at the PouchDB library to compliment Couchbase as your remote data store. PouchDB can prepare SQLite for syncing.

  • Juan

    Hi Nic,

    Great tutorial, i’ve a question, there’s a way to insert a blob value into sqlite?. I don’t want to store base64.

    Thanks, Juan.

  • Rajesh d m

    Hey im new to hybrid app development so my question might be silly

    My doubt is can this SQL Lite DB be used for making apps with IONIC ( which uses cordova ) and be compatible with windows apps also ?
    And can you please tell me if there are any other options ( like MongoDB or PostgresSQL DB ) which can be used for hybrid app development.

    Thanks in advance

  • Rajesh d m

    Amazing post. very useful

    I have a doubt
    Im new to hybrid app development. I wanted to know if SQL lite can be used as the DB for IONIC(which runs on cordova) apps even for windows 8 mobiles ?

    Also could you tell me about any other alternatives for DB which can be used for creating hybrid apps which run on all 3 platforms?
    Thanks in advance

    • The SQLite plugin might work for Ionic, but I honestly don’t know. Last I checked Windows Phone wasn’t supported with Ionic, but maybe things have changed now?

      In terms for a cross compatible database, you might want to check out the PouchDB library with a Couchbase back-end.

      Regards,

      • Rajesh d m

        Thanks a lot. Will check out PouchDB.
        And ionic now supports windows 8

        • Please share a link that states Windows 8 is supported and not just alpha.

          Regards,

          • Rajesh d m

            My friend told me it is now compatible (i haven’t tried it myself yet).

            Here is a link which shows how to make apps for windows 8.1 and windows phone 8.1 using IONIC.

            https://www.hoessl.eu/2014/12/on-using-the-ionic-framework-for-windows-phone-8-1-apps/

            Hope this helps

          • Rajesh d m

            Hey did the link help ?

            and i had one more doubt. How do i print the data received from the database onto the screen( DEVICE SCREEN) instead of printing on the console?

            I tried assigning the rows received to a variable data and using it in the index.HTML file but it did not work, nothing is getting printed.
            Thanks in advance

          • I didn’t look at the link because I was looking for an official statement from Ionic. I really don’t think Windows Phone is supported, but I do however, think it has improved since the early days. Improved doesn’t mean supported though.

            As for displaying SQLite data, you may want to check this out:

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

            Regards,

          • Rajesh d m

            Thanks a lot, This link worked beautifully on the browser

            One problem, when i build it for android and install it on my phone, first it crashed and from next time it is just stuck at loading page

          • If we’re still talking Windows Phone, I cannot help you. I am pretty sure it is not supported in Ionic, and I don’t have Windows Phone experience.

            If it is Android or iOS what do your logs say?

          • Rajesh d m

            I’m testing it on my android phone (completely left aside windows for now). The problem is, my emulator is not working, so i’ building the app and transferring the apk to the phone and installing and hence have no logs.

          • See this tutorial:

            https://www.thepolyglotdeveloper.com/2014/12/debugging-android-source-code-adb/

            Works the same if you’re using a device or a simulator.

            Regards,

          • Rajesh d m

            Do we need to have an apple developer id (by paying $99) for just testing it on our device or just a MAC is enough for testing ?

            I just want to test it on my device, not publish it to the app store..
            Thanks in advance

          • I don’t know. I pay the $99 fee. You might consult the Apple documentation.

            Regards,

  • Warren Prasad

    Thanks Nic for this tutorial.

    Have uploaded the complete code in GitHub as a reference.

    https://github.com/warrenpd/IONICSQLite.git

    • Awesome! Thanks for doing that.

      Regards,

  • AnotherSceptic

    Can you just remove the page? Is does not work by itself and does not only add to anything out there, but even worse, it is plain wrong to not act on the OnDeviceReady event and you statte that at the end of the article. SQLite in cordova sucks bigtime and this tutorial did not help at all.
    Thanks for the effort though.

  • Online girls chat rooms join for free no registration needed 🙂
    Chat Rooms
    Asian girls chat rooms

  • Roonie Toon

    Can this issue test on web browser? Error happen

    “Uncaught TypeError: Cannot read property ‘openDatabase’ of undefined”

    • This is a native device plugin that cannot be tested in a web browser. You’ll have to use WebSQL instead if you wish to use in a web browser.

      Regards,

  • Hridaya Kandel

    Got this result when installing plugin
    F:ionic_projecttest2>cordova plugin add https://github.com/brodysoft/Cordova-S

    QLitePlugin.git

    Fetching plugin “https://github.com/brodysoft/Cordova-SQLitePlugin.git” via git

    clone

    Repository “https://github.com/brodysoft/Cordova-SQLitePlugin.git” checked out t

    o git ref “master”.

    shell.js: internal error

    Error: EXDEV, cross-device link not permitted ‘C:UsershridayAppDataLocalTem

    pgit1436483576358AUTHORS.md’

    dova-libnode_modulesshelljssrcmv.js:77:8

    _modulescordova-libnode_modulesshelljssrcmv.js:53:11)

    modulescordova-libnode_modulesshelljssrccommon.js:186:23)

    dova-libsrcplugmanutilplugins.js:53:19

    _modulesqq.js:787:54)

    escordovanode_modulesqq.js:816:30)

    _modulescordovanode_modulesqq.js:749:13)

    .js:557:44

    • I’ve not seen that error before, but a part of me thinks it is your Apache Cordova or NPM installation. You may want to post this in the forums.

    • Kapil

      npm install -g [email protected]

      • Smith Foto

        many thanks

  • Madhavrao

    If I use Sqlite with IONIC it leads to memory leak on ios. VM JS Garbage collector keeps on increasing, and does not decrease, and eventually crashes application.

    • You probably want to open an issue ticket with the plugin developer.

      Regards,

  • Gayan Liyanaarachchi

    When going to build using eclips this error is comming.

    The library ‘sqlite-native-driver.jar’ contains native libraries that will not run on the device.
    Additionally some of those libraries will interfer with the installation of the application because of their location in lib/
    lib/ is reserved for NDK libraries.
    The following libraries were found:
    – lib/arm64-v8a/libsqlc-native-driver.so
    – lib/armeabi/libsqlc-native-driver.so
    – lib/armeabi-v7a/libsqlc-native-driver.so
    – lib/x86/libsqlc-native-driver.so
    – lib/x86_64/libsqlc-native-driver.so

    can anyone tell why is that?
    http://forum.ionicframework.com/t/sqlite-native-driver-jar/28534

    • I’m sorry, but I don’t use Eclipse or any other IDE. This issue seems isolated to Eclipse, but I recommend you posting the issue in the forum.

      Regards,

      • Gayan Liyanaarachchi

        Thanks for try Nic.If I got solution i will post it for others.

  • arist1213

    Nice work, but seems the latest sqlite module have some problem with building. I change the module to old release version, it works perfect.

    https://github.com/litehelpers/Cordova-sqlite-storage/archive/r2014.09.zip

    • I think you are correct. I think the latest version is having problems with a lot of people.

      Thanks for sharing your fix!

  • mikey

    Hi Nic, thanks for this tutorial.. Saved me =)

    Now I am required to sync my SQLite data with my main database(MySQL) when ever there is an internet connection.

    Please help me.. Cheers !!

  • Pranav Ranjan

    Hi Nic,

    Thank you for this tutorial, worked on iOS and Android emulators. For android, although it puts the output to the console I see the following message.

    exec() call to unknown plugin: Console

    • Sounds like you’re missing a plugin for whatever reason. Maybe try running:

      And see if it corrects your issue.

      Regards,

      • Pranav Ranjan

        I tried remove and add of the plugin but the message continues. Not an issue for me as I can see the output to the console.
        Thanks

        • Yea if it isn’t causing you issues, just ignore it. I’ve not run into this myself.

  • leocaseiro

    I took a while to find out how to parse a loop from the SELECT, so it’s easier than I was expecting.
    I’ll put it here, so that can help others:

    if(res.rows.length > 0) {

  • Saurabh AV

    Hi, how does SQLite compare with PouchDB?
    And is there a 5MB restriction when using SQLite?

    Thanks

  • Thanks for the great tutorial, I’m exploring best approaches on how to deal with database changes in future, adding a new table columns and how you will determine which version of the database the user has installed and update if needed and preserving existing data.

    Please share your ideas or experience on the subject matter?

    • Even though I’ve shown that SQLite is possible with your applications, it is not the best approach. I recommend a NoSQL approach for mobile applications, whether that be with local storage or something like Couchbase. Unstructured JSON storage is the way to go.

      Regards,

      • Thanks for the advise…

      • Since we on the topic of NoSQL approach and doing a bit of research, PouchDB seems to be the best approach – I have searched your blog and couldn’t find any topics that could guide me more on the PouchDB approach using ionic specifically…maybe a tutorial in future would be great, it would be interesting to see your implementation, especially synchronizing data with a RESTful API / PouchDB Server

        • I don’t only make tutorials on my blog. I post on other popular blogs which is why you didn’t find a PouchDB article on my own.

          It is a valid approach, but it isn’t the only one. Depends on everything you plan to accomplish.

          Regards,

          • Thanks – it took me three weeks just to make a decision on data storage based on your first reply, it was worthy – I can confirm that NoSQL is the best approach for hybrid apps (my opinion) – ngStorage all the way for me!!!

          • Awesome! Glad I could give you some insight 🙂

  • Jaini Pavan

    Hello Nic

    I have build my app and run in my android device, i am unable to find the locally stored database file in my device.

    • Databases are created on one of the protected partitions on the device. You can only access these partitions if your device is jailbroken or rooted.

      Regards,

  • Rakesh L

    Very good tutorial . Helped me a lot .. Thanks for the post

    • No problem!

      • Rakesh L

        Hi I face the problem in the date and time insertion .

        http://stackoverflow.com/questions/32763273/ionic-stuck-with-insertion-of-date-and-time-into-sqlite-table

        I have project delivery today.Can you please help me ?

        • Here’s the deal.

          I’m happy to help you, but you need to not post three times, the same comment. Every time you comment, everyone who has ever commented will receive an email.

          Second, I’m not going to help you when you link to a third party resource such as Stack Overflow. If you want my help, post your question here because I’m not going to travel elsewhere to answer it.

          Regards,

          • Rakesh L

            I was not aware of the email notifications you mentioned. I would like to say sorry to you for that . I have mentioned my query below. Please help me for the solution.

            I am very new to the Ionic framework. I have tried to Insert varchar into the table and it works as well.

            But,when I tried to insert date or time ,it shows an error Prepare statement failed with error 1 .

            Inside .ready() function, the database and table is created as mentioned below,

            Inside the Controller, tried to insert the values in two ways as mentioned below,

            Way 01:

            Way 02:

            But,unfortunately the same error is displayed.

            Please help me finding the solution.

          • Per the SQLite spec it doesn’t look like you can use the data type of DATETIME:

            https://www.sqlite.org/datatype3.html

            Honestly, I would store the epoch time which is a numeric. Then you can use JavaScript code to format that time when you need to display it. It will make your life so much easier.

            Best,

  • Bernhard Zürn

    A working (Android) implementation can be found here: https://github.com/zuernBernhard/sequel

  • Darrin

    Hi, I’m new to this but can you help, I’m using VS2015, Cordova, Camera Plugin, Ionic and sqlite. I have sqlite working great the problem. The problem is saving a photo(Blob) to the database, no I’m not sure if I am getting the URL correctly(or converting it) or if I’m not saving it correctly. Does anyone have a simple way of adding a photo? Thanks.

    • I recommend you do not try to store your pictures in the SQLite database. You should store the filename and path it exists in on the filesystem in the SQLite database and then access it via that path when you’ve discovered it in the database.

      Regards,

      • Darrin

        Thanks for replying, the reason I want to put them as a BLOB is I will be syncing up with a database further down the line and if its always in there as maybe a Basic64 string I won;s have to worry about users deleting it. Is there away of doing it?

        • There are better ways to store and sync images.

          If you have no interest in taking my advice, the best way to store images in SQLite is to convert them to base64 first. Maybe see this for making the conversion to base64?:

          http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript

          Regards,

          • Darrin

            Thank you, I’ll give it a go and I’ll let you know.

          • Darrin

            Hi, I have it almost working, the code I Have is this

            function onSuccess(imageURI) {
            var canvas = document.getElementById(‘canvas’);
            var context = canvas.getContext(‘2d’);
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            imageObj.src = imageURI;

            All is ok under ripple emulator I get a base64 text string in testpic, but once I install it on my phone the testpic element is blank. Any ideas?

            Darrin.

          • What do your logs say?

          • Darrin

            Logs on my Phone? how would I get to them?

  • Bon Lemuel Dela Cruz

    Hi Nic, do you have a method on ‘Updating’ a row? Thank you.

    • SQLite is just SQL. You can execute an UPDATE statement.

      Regards,

      • Bon Lemuel Dela Cruz

        Alright, Thanks you! 🙂

  • Bon Lemuel Dela Cruz

    Hi Nic, how do you update a certain row on the table? Thanks

  • Dha Fkff

    Hello Nic,
    Can you tell me how to delete all rows of table using sqlite in ionic apps.

    • Umm…. what’s wrong with this?:

      DELETE FROM table_name_here

      Just execute that query and it will delete all rows.

      Regards,

  • kennith

    Great!!!! Helped me a lot. Thank you NIC.

  • Hi ! I have problem with the Insertion of Date and Time . Please help me resolving . I have posted my query in detail in stackoverflow .

    http://stackoverflow.com/questions/32763273/ionic-stuck-with-insertion-of-date-and-time-into-sqlite-table

    Please help me .

  • Christian Ndoradoumngue

    Hello, sir!
    I would like to connect my app to a relational database such as PostgreSQL. Can you please, help me do that?
    Thanks

    • That is no small task. I would not recommend using a relational database with any mobile application because it is a nightmare when it comes to synchronization. Your best bet is a NoSQL solution. You might check out this:

      http://blog.couchbase.com/using-couchbase-in-your-ionic-framework-application-part-1

      If you still truly want to use a relational database, your best bet would be to create a RESTful API application server. Again, not a small task.

      Best,

      • Christian Ndoradoumngue

        Alright. I would go for NoSQL. Thank you so much for the quick reply.

      • Christian Ndoradoumngue

        I am thinking of using a Jquery that will convert my app json and insert it into the relational database. I am insisting on this because I imagine how hard it would be to convince the client to change his/her whole database or build a new one for an app you are creating for him/her.

        • I hear you. It is always painful to make such a major change. NoSQL is taking over though so it may be beneficial for you and your client to look at sooner than later. Applications love JSON, and if the database does too, then it is a perfect match.

          Your best bet, if you want to stick with a RDBMS, would be to create a RESTful API as jQuery will not be able to save directly into a relational database.

          • Christian Ndoradoumngue

            Great! Thanks

          • No problem!

  • Hi Nic, thanks for all! See my example using service pattern: https://gist.github.com/jdnichollsc/9ac79aaa3407e92677ba

  • kkai316

    Hello Nic, I wonder if it’s possible to put SQLite syntax outside the function but in controller. I am working on a project that need to detect if the table is empty then do something. So I use “SELECT count() FROM myTable” in my controller to check if the table is empty. However, my device showed blank. If I put “SELECT count() FROM myTable” in a function then it display correctly. It’s tested on real device. Do you have any good suggestions? Thank you

    • What do your logs say?

      • kkai316

        Never mind, I came out a better way to work on the project. Thank you for your reply!

  • Mark Aurit

    Great Nic, thanks much for your articles. I have an architectural question to run by you: my ionic app will be pulling data from a remote sql server via a middle rest layer; not a lot of data, but a number of different queries that summarize and normalize data. I’m wondering if at start-up I should massage the data in sql server, pull it into sqllite, and perform my queries there. Its a real app so I don’t want to go down that road if someone with experience tells me its a fun experiment but not really good for prime time. Any advice would be greatly appreciated.

    • You’re probably not going to like this answer, but I would ditch the SQL ideas. If you only do RESTful requests without SQLite you risk an unusable app when no internet exists. If you include SQLite you’re going to need synchronization, like it or not.

      I’d switch to NoSQL and use sync tools that already exist. Example being PouchDB or Couchbase Mobile. These are things designed for modern apps. Offline first apps are where it’s at now.

      Best,

      • Mark Aurit

        Hmm .. I can see I didnt explain things well; the idea is to support fast response and a lack of connection. The only use of the rest api in this context is in pulling data down from the remote database to the local sqllite, and this would be under user control.
        In any case I’ll take your architectural disrespect as a challenge … 🙂 🙂

        • Think about it for a second.

          Your REST API is going to respond with JSON. Why would you want to do a double conversion on your data. By double conversion I mean creating the JSON server side and then converting it back into SQL client side. Why not just store it as JSON (NoSQL) server side and JSON (NoSQL) client side? Or at least store it as JSON client side and not convert back into SQL.

          Just my opinions on efficiency 😉

  • Aravind S

    Thanks a ton buddy! Works like a charm 🙂

  • Earl

    Hi,
    Is there a way to debug the sqlite database when I run my app to a ios device? I would like to check if the data have have been created into the DB.
    Thanks

  • Saqueib

    Thanks for posting awesome articles about all thing ionic 🙂

    I wanted to use SQLite to use as cache for all api calls, so that app can run while there is no internet.

    I was thinking about this structure for table

    What you think about this table structure ?

    or it will be enough to use localStorage for API response caching, But there is limit of 3-5mb for local-storage, that can cause issue, for example. If I have 20 endpoints and all data will be cached, then it will surely cross this limit. and upon updates sometime localStorage get cleared.

    I heard that iOS (app store) is not going to accept this app, since SQLite db wont backup to iCloud? whats the work around to this.

    Please help.

  • Anderson Murakami

    Where is the folder of file my.db ? I want to use SQLite Administrator Tool, but I am not find the my.db file in project folder.

    • It is in the protected space of your device. You won’t be able to find it unless you have a rooted / jailbroken device.

      Regards,

      • Anderson Murakami

        But I´m using in my PC. Running IONIC serve, in browser. I´m want use SQLite Administrator to know the data storage in Database. Have no location to database ?

        Thank´s in advance

        • I cannot stress this enough. Do not use ionic serve, ionic view, or ionic live-reload for testing your applications. You’re building mobile applications, not web applications. These services don’t know how to properly handle plugins.

          Regards,

  • Jonah Nisenson

    Hi Nic, this is relevant to @christianndoradoumngue:disqus question about using PostgreSQL. I have a Web App that uses a PostgreSQL DB because the data is highly relational and is not a good fit for Document DB. I’m using Breeze.js with Breeze-sequelize npm module to easily query the DB. The stack is BPEAN (Breeze Postgres Express Angular Node). I have an Ionic Mobile App that hits the Web App API and also uses Breeze.js. Though I haven’t yet gotten to implementing this sync solution from Breeze.js http://breeze.github.io/doc-js/export-import.html, it looks like it will do the trick using lawnchair for storing the Entity caches and making syncing pretty straight-forward. I won’t lie, there were some hiccups getting up and running with breeze-sequelize and using the Metadata was a pain at first but now that I’ve got it all working, I’m really loving Breeze.

    My question is, have you ever used Breeze.js and furthermore Breeze.js in Ionic. If so, what was your experience like. I believe that it is potentially a great way of using Ionic in conjunction with a relational DB.

    Oh, and how is this all relevant to sqlite in this post? I’m going to use sqlite for caching offline maps in conjunction with leaflet.js. Not yet implemented but that’s the plan.

    • Hey Jonah, I am not familiar with Breeze.js or that particular stack. I could have understood this incorrectly, but it sounds like you had to jump through a lot of hoops to get this working. What happens when something changes in one of the many moving parts of your project? Will you have to go back to formula?

      Would be interesting if you could spin up an example project on GitHub that demonstrates all this.

      Best,

      • Jonah Nisenson

        Hey Nic, thanks for the quick reply. The project is for a client so I can’t share directly though I intend to put a stripped down version on GitHub when i have things working. Yes, there were definitely hoops to jump through to get Breeze working with Node and Postgres but mostly because the documentation was lacking for breeze-sequelize. Will update you when I have something to share.

  • Jonah Nisenson

    For anyone else getting this error TypeError: Cannot call method 'transaction' of null when trying to call the $scope.insert method or the $scope.select method, even after trying the tricks mentioned below, I pulled my hair out for at least half a day. Turned out installing the plugin ionic-plugin-keyboard did the trick.

    • Doh!

      Yea sometimes the stock Ionic plugins that ship with the templates get wonky and need to be re-installed.

    • m1nka

      Thank you so much !

    • hasan gilak

      for better debugging i opend chorme://inspect and watch my console from there . my error was :
      Uncaught Error: Database location or iosDatabaseLocation value is now mandatory in openDatabase call
      this is ng cordova sqlite github page which help me find this fix :
      db = $cordovaSQLite.openDB({name: “my.db”, iosDatabaseLocation: ‘default’});

      • ishara withanage

        Thank a lot hasan u saved my day

      • zuki

        sir what if android? ill use “androidDatabaseLocation:’default'”?

        • hasan gilak

          I have to use it for Android to make it work also

  • Pedro

    Hello Nic,
    first of all, thanks you for this post and all the other posts about Ionic.
    Everything is working as expected, my question is more about performance and the correct use of those methods.

    I’m developing an app that has as a main screen a list of users and some of their info. This info can be increased or decreased by 1 in a click of a button and this button will be clicked a lot.
    My current implementation does the following:
    – User click the +1 button
    – An update query is executed to update the info value to +1
    – After the update query, I call the updateList method, another query to get a new list with the updated info.
    – Show the new value on the screen.

    This whole operation takes quite some time (1 second is relevant in this case), I mean, if you wish to update the info 3 times in a row, you need to tap the button, wait a second, tap again, wait another second and tap again.

    What can I do to improve this operation?

    My methods to add and update are a bit more complex version of this one: https://gist.github.com/lykmapipo/6451623a54ef9b957a5c

    Thanks again for the great articles.

    • 1 second is a long time. How much data are you updating in that single statement? I would expect your 4 step process to take a few milliseconds making it seem instant.

      My guess is one of your queries or manipulation logic pieces is coded inefficiently, but I can’t say for sure. Can you give me more information about your process?

      Best,

      • Pedro

        I’m not an expert in database or SQL but I’m pretty sure updating a single value from a single column shouldn’t take this long… I would like to make it instant.

        This is all I’m using to update the value:
        http://dontpad.com/codesnipets

        Two services, one DBA and another to manipulate my players table
        Two functions to update the values inside the controller
        and using the $scope to show my list of players in the view.

        • It seems alright to me. However, I personally would only refresh the particular array item, not the entire array every time I made an update. Querying for X amount of records every time could be expensive.

          • Pedro

            But that’s what I thought I was doing in this query UPDATE players SET level = (?) WHERE id = (?)
            Updating just the level, isn’t it?

            Oh I’m sorry, I see now. Instead of updating all the players after and update, I should update just the one I just changed.
            I’ll try that, thanks!

          • Yea your queries seem fine and quick, it is everything else that can be improved 🙂

          • Pedro

            The problem is actually ng-repeat. I’m trying to improve the view using collection-repeat. Thanks for the help anyways!

          • No problem!

  • Is that possible to load pre-build DB using this plugin? i.e I want to load a database I’ve created using MySql that contains some data.

  • Gian Luca Scoccia

    I just wanted to point out that rather than create a global variable to hold your database connection you can use a angular .value ( https://docs.angularjs.org/api/auto/service/$provide#value ) and achieve the same effect with a slightly more pleasant syntax 🙂

    Aside from this, very nice tutorial, saved me a lot of time.

    • That looks like it could be very useful. Thanks for sharing it 🙂

  • Irshad Gauri

    Great blog Nic
    I have used cordova sqlite plugin in my app and its working fine.
    But when I updated cordova version and android sdk, then it give error that sqlite api depricated.
    Could you please help me to solve this problem ?

    • You’d have to bring it up with the plugin developer. He’ll need to update the plugin to accommodate the latest Android SDK.

      • Irshad Gauri

        Thanks for your reply. Plugin needs modification, till then I can either use previous sdk or cordova version.
        Can you please suggest me android api level and cordova version to be use with this plugin. Thanks in advance !!

        • I keep 16 to 22 installed, but you should really be asking this question to the plugin developer.

          Regards,

          • Irshad Gauri

            Thanks.

  • Shantanu Acharya

    @nicraboy:disqus I am following your tutorial, saved much of time in learning Ionic thanks to you. Am having an issue related to $cordovaSQLite Ex: am having an associative array of users information (not more than 15 records) which is to be inserted into users table and after complete insertion redirect user to different view, used angular.forEach and am running $cordovaSQLite.execute in it before complete insertion of users the view is changed (asynchronously). Is there some another technique which am not aware of as in am new to cross-platform application development.

    • Different technique for what?

      • Shantanu Acharya

        am having an associative array of users information (not more than 15 records) which is to be inserted into users table and after complete insertion redirect user to different view, used angular.forEach and am running $cordovaSQLite.execute in it before complete insertion of users the view is changed (asynchronously)
        The code doesn’t execute sequentially the data within for each loop executes asynchronously and before storing all data the page is redirected.

        • Yes I saw what you wrote, but it made no sense. Instead of copy pasting what you wrote, how about try explaining.

          Regards,

  • Manuel Vasquez

    When I execute the command “ionic serve”, the browser console displays the following:
    TypeError: n.sqlitePlugin is undefined ng-cordova.min.js:9:30124
    .openDB() ng-cordova.min.js:9
    app.js:27
    .$get</self.ready/<() ionic.bundle.js:53329
    onPlatformReady() ionic.bundle.js:2491
    onWindowLoad() ionic.bundle.js:2472
    Why’s that? How can I fix it?

  • Manuel Vasquez

    How can I access to the console of the iOS emulator on Mac OS?
    And when I try it on a web browser using the command “ionic serve” the js console of the browser displays the following:

    TypeError: n.sqlitePlugin is undefined ng-cordova.min.js:9:30124
    .openDB() ng-cordova.min.js:9
    app.js:27
    .$get/self.ready /() ionic.bundle.js:53329
    onPlatformReady() ionic.bundle.js:2491
    onWindowLoad() ionic.bundle.js:2472

    • You realize you sent me four messages today right? You also realize I do other stuff throughout my day right?

      You should probably check this:

      https://www.thepolyglotdeveloper.com/2015/10/how-to-get-programming-help-in-forums-and-on-my-blog/

      Regards,

      • Manuel Vasquez

        Yes, and I did it because the posts sorting was displaying another
        posts instead of mine, so I thought that there was a problem with the
        web page and I sent a lot of posts, once I changed the posts sort
        options and saw the 4 messages I deleted 3 of them, and of course
        everybody has another activities during the day I wasn’t trying to be
        annoying or insistent.

  • Manuel Vasquez

    How can I access to the console of the iOS emulator on Mac OS?
    And when I try it on a web browser using the command “ionic serve” the js console of the browser displays the following:

    TypeError: n.sqlitePlugin is undefined ng-cordova.min.js:9:30124
    .openDB() ng-cordova.min.js:9
    anonymous app.js:27
    .$get/self.ready /() ionic.bundle.js:53329
    onPlatformReady() ionic.bundle.js:2491
    onWindowLoad() ionic.bundle.js:2472

  • Manuel Vasquez

    Great tutorial!

  • Manuel Vasquez

    Yes, and I did it because the posts sorting was displaying another posts instead of mine, so I thought that there was a problem with the web page and I sent a lot of posts, once I changed the posts sort options and saw the 4 messages I deleted 3 of them, and of course everybody has another activities during the day I wasn’t trying to be annoying or insistent.

    Regards.

  • adnan chowdhury

    Hi Nic, where is the db file located physically in my device, how can I mention that? I want to store some image files in the same location ….

    • The database is stored in the protected partition of your device. You don’t store files in that area. Files are either to be converted to a base64 string and saved into the database or stored in the SD partition of your device.

  • John Doe

    Hey Nick ! Excellent work for your tutorial! they help a lot !

    I
    am encoutering issues while fecthing data within a DB through a
    factory. Actually, i just want to do a simple SELECT id FROM users;
    query and I can’t manage to do that.
    I expect the query to return
    the result in a controller and then print out the result in the view
    through the ng-repeat directive in order to list all users in my DB.

    Here is my factory :

    app.factory(“DatabaseService”, function($cordovaSQLite, $q){
    var liste = new Array();

    })

    Here is the controller :

    app.controller(‘HomeCtrl’, function($scope, DatabaseService){

    and here is my view

    Hope you can help me !!

    Cheers,

  • John Doe

    Hey Nick ! Excellent work for your tutorial! they help a lot !

    I
    am encoutering issues while fecthing data within a DB through a
    factory. Actually, i just want to do a simple SELECT id FROM users;
    query and I can’t manage to do that.
    I expect the query to return
    the result in a controller and then print out the result in the view
    through the ng-repeat directive in order to list all users in my DB.

    Here is a gist of my files https://gist.github.com/RobinDesir/04947f855028259c301f

  • Reza Primasatya

    All step in this tutorial I was follow but still got error Uncaught TypeError: Cannot read property ‘openDatabase’ of undefined. Any body can help ?

    Thanks

    • What do your full logs say?

    • m1nka

      Just had the same error. Its because sqlite plugin isnt there. You should test this tutorial on a device not ionic serve. There is no sqlite plugin in your browser ….

  • Wilmary Laclé

    Thank you soooo much 🙂 Greetings from Venezuela

  • Surya Jolly

    Hi Nic, Thanks for this tutorial. One doubt regarding testing, Can i test ionic app using sqlite from web browser(ionic serve). Since my ionic android emulator from CLI, is taking long time to launch the app , any other option is there to test the app.?(I am using a windows machine and trying to build an android app using ionic and ang js)..
    Thanks

    • Web browsers are for web applications, not mobile applications. I recommend using Genymotion as your Android emulator since it is like 1000x faster than the stock Android SDK emulator.

      Best,

  • Solwind

    Hi there. You stated that you are not making “database calls from inside an onDeviceReady() function.” But what does an “onDeviceReady()” function look like? I’d like to fire these at the start of my app launch as well as periodically update the database every X amount of seconds. I understand that using a native plugin like this would cause errors on ionic serve… But it isn’t saving the data when I run my emulator either.

    • Native plugins cannot be used until the device is ready. At a basic level, Apache Cordova has an onDeviceReady() function. If you’re using Ionic you probably want to use the modified $ionicPlatform.ready() function. These functions get executed when the device is ready.

      Best,

  • Leonardo Mendonça Piazzoli

    I just wanted to congratulate you for answering 376 comments.
    And share a solution to run OpenDB before running the SELECT Controller.

    app.js:

    $ionicPlatform.ready(function () {
    db = $cordovaSQLite.openDB(“my.db”);
    alert(“HERE 1”);
    });

    controller:

    $ionicPlatform.ready(function () {
    alert(“HERE 2”);
    // SELECT
    });

    Thus alert 1 comes before alert 2

    I hope you’re not talking wrong.

  • mithu

    it is a good blog.It is very informative.Our websphere course is enough for anyone who wants to get websphere certification which meets industry expectations.

  • mithu

    it is a good blog.It is very informative.Our websphere course is enough for anyone who wants to get websphere certification which meets industry expectations.

    websphere-trainingchennai

  • mithu

    it is very nice blog.thanks for share this.Our websphere course is enough for anyone who wants to get websphere certification which meets industry expectations.

    websphere-trainingchennai

  • Theo Affail

    Hi i need help big time. I tried using this and every time i add the insert chunk of code it breaks my UI, just by adding it.

  • Shishu Singh

    Hi NIC,
    i have a Db in SqlLite and i want to fetch data from this particular Db…..so plz help me out to do this task…..actually i tried the above example to create a new db but it not created……i want to know that where i can found that particular” my.db” i my project folder.

    • The DB is created in the devices protected space, not a folder.

      What do your logs say? What platform are you trying to use? Etc. Have a look at this:

      https://www.thepolyglotdeveloper.com/2015/10/how-to-get-programming-help-in-forums-and-on-my-blog/

      Regards,

      • SAM KHAN

        HI Nic Raboy.. thanks for your good article and support .. i went through your article but after installation its works first time and when we close the app or we tap on back button and again opening the app then its give us a error transaction of undefined … please help us or please make an article on lates plugin.

        • What do your full logs say?

          • SAM KHAN

            thanks for your support Mr. Nic Rayboy .. problem has been solved now but i have another issue i.e. i am retrieving image from pre-populated sqllite db which has Place_of_Interest and there is a Place_Picture column and that column containing .jpg files ..now i want to retrieve those images in my placedetail.html please help me would be your kind. Just give me syntax if you are busy. thanks

          • Again, what have you tried and what do your logs say?

  • SAM KHAN

    HI There …. can anyone help me please .. i m fetching data from pre-populated sqlite db through ionic framework but on installation time firstly its works and give the data but after closing the app and opening it again but give error that ‘transaction’ of undefined ..

  • Jenilia Mohan

    thanks for sharing about sql using framework. and your code explanation of database connectivity is very much useful for our academy candidates.

  • Rodrigo Torres

    I have this error:

    TypeError: Cannot read property ‘transaction’ of null

    I’m using Intel XDK to emulate the app! Please, help me.

  • Krishna Karki

    Thank you Nic for sharing. How we can prevent sqllite data backing up on ios icloud?
    Will it work if we open database with locaiton like this?
    $cordovaSQLite.openDB({ name: “my.db” , location:1 });

    • You’d have to use “location: 1”, but it isn’t supported in ngCordova. You’d have to either open a ticket with the project maintainers or drop ngCordova and use the vanilla JavaScript plugin:

      https://github.com/litehelpers/Cordova-sqlite-storage

      Although less convenient, you’d probably be better off using the vanilla plugin without the ngCordova wrapper.

      Best,

      • Krishna Karki

        Thanks Nic. I used
        db = window.sqlitePlugin.openDatabase({ name: “my.db”,location: 2, createFromLocation: 1 });
        after researching a lot. I dont want to sync my sqllite db to icloud so i used 2.
        And submitted app today for ios review. I hope my app will not reject.
        And thanks lot for sharing your knowledge. Really you are helping many developers through your blog.

        • I think it will get accepted, no problem! I’m glad you found my material beneficial.

          Best,

  • alby111

    I would like to insert data from a csv file in a sqlite for android. I added this code into the www js app.js

    I tried the csv located in different directories: www js and www

    After creating the database, I can´t get to load the data from csv.

    (.csv Example: firstName111, lastName111, telephone11, email11, note111)

    ` angular.module(‘starter’, [‘ionic’,’ngIOS9UIWebViewPatch’, ‘starter.controllers’, ‘starter.services’, ‘ngMaterial’, ‘ngMessages’, ‘ngCordova’])

  • Guna Sekhar

    Can you please tell me how to implement database in Windows phone.

    • What have you tried and what isn’t working?

      • Guna Sekhar

        I am using Cordova-sqlite-storage plugin, tried storing two text fields.

  • Jed Nocum

    Thank you so much! I was having a problem lately and it says “uncaught error database location is now mandatory”, so I searched for the plugin in github and it says

    Recommended:

    db = $cordovaSQLite.openDB({name: ‘my.db’, iosDatabaseLocation: ‘default’});

    So i tried mine like in the above codes and it work. calling

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

    OR

    db = $cordovaSQLite.openDB({“name: my.db”});

    does not work for me and I dont know why lol. I think maybe the plugin has been updated or what.
    Just sharing this if someone got the same problem like mine. Thanks sir Nic!

  • Bruno Costa

    Alguem poderia me ajudar nesse projeto, esta dando um erro muito estranho

    https://github.com/bhcosta90/ionic

    Tipo, ele fala q nao estou usando o plugin, porem quando eu clico no botão listar ele funciona normalmente. Eu estou usando o android 5.1 se alguem puder me ajudar

  • chamod jayasundara

    when I run the app in emulator “Type error:cannot read property transaction of null” and few errors show in adb logcat

    • Can you confirm that the db variable is not null when you try to use it? Want to rule out whether or not it is being set when you try to open your database.

      Best,

      • chamod jayasundara

        actually it is null.So what i do?

      • chamod jayasundara

        db = $cordovaSQLite.openDB({name: “dbname.db”, location: 1}); .I use that line like this its working…

  • ishara withanage

    A Great tutorial.. I would like to how to retrieve data and display them within interface rather than console..? For the select query you have written i want to display those values

    {{title}}

    like within tags

  • Hitendra

    hello, i am facing this issue when i am trying to add the plugin into my project.
    i am unable to find any exact solution. Any Idea whats wrong.

    >

    Error: Failed to fetch plugin https://github.com/brodysoft/Cordova-SQLitePlugin.git via git.

    Either there is a connection problems, or plugin spec is incorrect:

    >

  • Hitendra

    hello, i am facing this issue when i am trying to add the plugin into my project.

    i am unable to find any exact solution. Any Idea whats wrong.

    >

    Error: Failed to fetch plugin https://github.com/brodysoft/Cordova-SQLitePlugin.git via git.

    Either there is a connection problems, or plugin spec is incorrect:

    Error: “git” command line tool is not installed: make sure it is accessible on your PATH.

    >

  • Chad Tetreault

    Hey Nic, following the guide with Cordova 5.1.1 and Android platform @ 4.0.2

    Getting the following testing live on a device when attempting to open a database using this guide.Nothing else, no additional error(s) to go on.


    OPEN database: hello-world.db

    SQLitePlugin.js:191 OPEN database: hello-world.db failed, aborting any pending transactions…

    I have confirmed that ngCordova is installed, the plugins are installed, and that $cordovaSQLite is available as shown.

    Not much to go off of I know, hoping you might have some tips. 😉

    -chad

    • What if you do this instead?:

      I think the ngCordova implementation might have changed.

      Let me know how it goes.

      Best,

  • Gopinath Kaliappan

    projectpath/cordova-sqlite-storage/node_modules/cordova-sqlite-storage-dependencies/libs/sqlite-connector.jar” not found!

    Getting the above error while adding sqlite plugin

  • Kadeem Vers

    Hi this tutorial is awesome, but i have an strange error and i’m very new to ionic en angular js. Can someone please help me solve this problem. Check the error in the attached picture

    • Are you trying to use this with ionic serve or in a web browser?

      • Kadeem Vers

        with ionic serve. I forgot to say that i downloaded the newst ionic 2 beta version and i can see that some of the default blank template code in de app.js and in the home.js is diffrent then your version of the default blank template see the foto’s below of the app.js and the home.js

  • 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 “NFCTAG.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.

  • Nikhil

    if you are using ionic 1.7.14, platform ios 4.1.1 and cordova-sqlite-storage 1.4.1 then please use the following line to open the connection. I spent couple of hours before I realised this was the issue.
    db = $cordovaSQLite.openDB({name: ‘my.db’, iosDatabaseLocation: ‘default’});

    • Alexander Galkin

      +1
      parameter is called location now.

      dbConnection = $cordovaSQLite.openDB( {
      “name” : “mydb.db”,
      “location” : “default”
      })

  • Periyasamy M

    How to see my db file? what is the location of db file?

    • The database exists in the protected partition of your device. You cannot access it outside the application unless you have rooted or jailbroken your device.

      Best,

  • Periyasamy M

    I complected all the Steps filnaly i run my app in chrome://inspect/#devices.i find the error is
    SQLitePlugin.js:563
    Uncaught Error: Database location or iosDatabaseLocation value is now mandatory in openDatabase call.

    how to i clear this error?

  • rupen

    For Ionic, Cordova on Visual Studio, should we use below format ( provided in your article)

    $cordovaSQLite.execute(db, “CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)”);

    Or below one (from https://github.com/litehelpers/cordova-sqlcipher-adapter ):

    var db = window.sqlitePlugin.openDatabase({name: ‘my.db’, key: ‘your-password-here’, location: ‘default’}, successcb, errorcb);

    Both are working in my case, however, I am confused which one is better. – I need to use SQLite + SQLCipher for encrypted database.

    • $cordovaSQLite which is part of ngCordova is only a wrapper to the window.sqlitePlugin to make it more Angular friendly. My personal opinion is to use the window.sqlitePlugin method because Ionic has a bad habit of breaking or not keeping ngCordova up to date with core Apache Cordova changes.

      Best,

      • rupen

        ok. One more difference may be that there is no password in cordovaSQLite.execute statement. right?
        this is present in window.sqllitePlugin statement. Further, what is the use of this password, as user can see it in Javascript source.

        • The key is for if you want to use the SQL Cipher extension. I always like using the regular plugin, no wrappers. The more tools you use, the more chances for failure.

  • startupfoundry

    Hi Nic,

    I’m having issues with SQLite in my Ionic app. It appears to work in browser (from “ionic serve”) but crashes on device (both iOS and Android) at launch. I can’t even seem to get any debug data out of it.

    I’d be happy to post any relevant files you request. I also have the entire app hosted on a private gitlab repo if you’d like to take a look.

    I appreciate your help and the tutorials you’ve been pumping out!

    Paul

  • Obi

    Hi Nic.
    Great tutorial & very helpful for a beginner like myself.

    I’m getting the error “Cannot read property ‘transaction’ of null”.
    Basically, I $cordovaSQLite.openDB() in the app.run() section, then in one of the controllers is a function which queries the db and returns data and logs the number of records returned.
    But the logs show the error above BEFORE the ‘DB opened’ log, so it’s as if it’s calling the controller function before the database is initialized/opened.

    Any ideas or suggestions?

    Thanks.

    • Sounds like you’re suffering from a race condition. Try moving the initialization logic into a controller. The run function is asynchronous and isn’t completing in time

      • Obi

        Thanks for the response, Nic. I guessed as much. I was hoping there was a way to call the controller only after the db initialization.

        I fixed it by encapsulating the db query call in the controller inside $ionicPlatform.ready().

        What’s your opinion on using a NoSQL database like CouchDB as opposed to SQLite? I’m wondering if would be faster and not cause a race condition, since it’s just a JSON document.

        • SQLite and NoSQL will have the same issue. If you try to do too much in the app.run method, the controllers will trigger before it finishes. Your best bet is to create a first controller dedicated towards initialization. Maybe throw a splash screen in it or a loading indicator. Then reroute when it completes.

  • Mangesh Narkhede

    06-15 22:07:24.805 29350 29350 I chromium: [INFO:CONSOLE(26794)] “TypeError: Cannot read property ‘transaction’ of null

    06-15 22:07:24.805 29350 29350 I chromium: at Object.execute (file:///android_asset/www/js/ng-cordova.min.js:9:20773)

    06-15 22:07:24.805 29350 29350 I chromium: at Scope.$scope.insert (file:///android_asset/www/js/app.js:26:24)

    06-15 22:07:24.805 29350 29350 I chromium: at fn (eval at (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:27638:15), :4:236)

    06-15 22:07:24.805 29350 29350 I chromium: at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:65427:9

    06-15 22:07:24.805 29350 29350 I chromium: at Scope.$eval (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:30395:28)

    06-15 22:07:24.805 29350 29350 I chromium: at Scope.$apply (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:30495:25)

    06-15 22:07:24.805 29350 29350 I chromium: at HTMLButtonElement. (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:65426:13)

    06-15 22:07:24.805 29350 29350 I chromium: at defaultHandlerWrapper (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:16787:11)

    06-15 22:07:24.805 29350 29350 I chromium: at HTMLButtonElement.eventHandler (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:16775:9)

    06-15 22:07:24.805 29350 29350 I chromium: at triggerMouseEvent (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2953:7)”, source: file:///android_asset/www/lib/ionic/js/ionic.bundle.js (26794)

  • Anish Sujanani

    Hello, the app seems to work fine in the emulator, however not on a real device. There is no data persistence on the real device.
    I have posted on stackoverflow and the ionic forums, no one seems to have any answers, any help would be appreciated!
    http://stackoverflow.com/questions/37853888/cordovasqlite-sqlite-db-not-persistent-on-android-device-works-fine-on-emulat
    Thank you!

  • amouna

    Hi t i have an error in this tutorial and i’m very
    new to ionic en angular js. Can someone please help me solve this
    problem. Check the error in the attached picture and thanks.

  • LUISAO

    Just see the excelent tutorial, thank you.
    After the tutorial, i just tried but happens some error Uncaught TypeError: Cannot read property ‘openDatabase’ of undefined

    because i try with ionic serve in browser Google chrome.

    To work with the browser, just see the link

    https://stackoverflow.com/questions/26101120/how-do-i-use-the-ngcordova-sqlite-service-and-the-cordova-sqliteplugin-with-ioni/28186445#28186445

    and it works, after i change

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

    to

    if (window.cordova) {

    Hugs from Salvador Bahia Brasil

  • Fahad malik

    First of all i want to thank for this tutorial. Its help me a lot.

    Second i want to ask you that how we can sync our sq-lite db with other devices using icloud. Currently my db is backing up at icloud but i am not able to receive that backup db on other device.
    Hopefully i will find reply here.

    Thanks

  • Mohaned Mansour

    i’m using mysql database
    how could i deal with this ?

    • MySQL and SQLite are both relational databases, but they are not the same. Based on the vague-ness of your question, I cannot provide any answers. Maybe give me some more details.

      Best,

  • 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
    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));

  • Valerio Radice

    Hi Nic I’m trying to compile and run for windows universal platform, I just use this plugin in .run() method and in ionic ready i use $cordovaSQLite.openDatabase but appear this error:

    0x800a01b6 – JavaScript runtime error: Object doesn’t support property or method ‘openDatabase’

    Can I do for fix it?
    Thank you

  • Aruna Nishantha

    Hi,

    Is there any way to upgrade schema of the application without loosing the table content?

    • You can use the ALTER command which is part of SQL

  • Dara Kaing

    sqlite size storage?

  • Mahiruho

    Hi NIck, I am getting this error in log ” A SQLiteConnection object for database ‘/data/user/0/com.google.android.gms/databases/metrics.db’ was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.” while runnig the app in emulator. I can’t find where should I close the database connection.

  • Yudha Praditya

    how if i use REST API? can i integrated with local DB?

  • Erick

    Hello, great article… someone can help me to generate a complete getData from my table? // SELECT * FROM mytable… instead of use a ‘for’ with – results.rows.item(#) – I want to get a complete json or object from this SELECT * // the problem is, the table has many columns, and I dont know the name the columns. Thanks in advanced

  • Darren Cole

    I’ve followed these instructions to a T and tried every suggestion here and on stack overflow. This thing just refuses to work. (snif!)

    • What happens? What do your logs say? How are you testing? Etc…

      The more you share, the better help you’re going to get here or anywhere else.

      Best,

      • Darren Cole

        Thank you for your response. I must apologise. My statement was posted at a point of much frustration. Today I paid attention to the logs and saw what was happening. The major thing was that I had to use:
        db = $cordovaSQLite.openDB({ name: “my.db”, location: ‘default’ });
        instead of:
        db = $cordovaSQLite.openDB({ “my.db” });

        The same goes for deleting the database:
        $cordovaSQLite.deleteDB({ name: “my.db”, location: ‘default’ });

        Regards,

  • John Piper Mayer

    Hello Nic, thanks for your tutorials.Do you know if I can read a database file with ionic (like ‘database.sqlite’) , i mean, not create, update or delete tables/rows and populate from scratch), only select rows with queries
    I was debugging on chrome because i cant see the database file on my mobile, but it dont load the rows from the database file
    i was asking me if opendatabase is the problem

    if (window.sqlitePlugin !== undefined) {
    // debugging in the device
    database = window.sqlitePlugin.openDatabase({ name: “database.sqlite”, location: 2, createFromLocation: 1 });

    } else {
    // debugging in the browser
    database = window.openDatabase(“database.sqlite”, “1.0”, “Database”, 200000);
    }

    Thanks for your help!
    John

  • Clare

    Hi,

    Constantly getting the error SCRIPT5007: Unable to get property ‘openDatabase’ of undefined or null reference

    I’ve tried from the comments below and my current code is:
    db = $cordovaSQLite.openDB({ name: “my.db”, location: ‘default’ });
    $cordovaSQLite.execute(db, “CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)”);

    Any suggestions??
    Currently running through my browser for testing!

    • You cannot test native device plugins in the browser.

  • Harjinder Singh

    that is not working
    pls help me

  • Manjunath Shenoy

    Thanks Nic for such a wonderful and step by step tutorial. I have followed and able to set up the ionic app. I have one query though

    I have SQLite db installed on my local windows machine. My application starts and runs successfully .Also, am able to add data to the database. However, in order to debug and ensure that data is stored in the DB I wanted to open the “.db file” in my local windows machine.For some reason am unable to find the .db file. Basically, i wanted the .db file to be opened with DB Brower for SQLite. Are these “.db files hidden” ?Could you please suggest?

    • Once installed, the SQLite database is stored in the protected space of the device. It cannot be accessed unless your device is rooted or jailbroken.

      • Manjunath Shenoy

        is there any other way to debug then,instead of me manually entering the data into the db?

        • Well you’re building apps and that is really just how it is. Maybe load mock data via a script? Don’t really know what you’re trying to do.

  • Thanks for the awesome share
    We at Colan Infotech Private Limited best web design company in chennai,is Situated in US and India,
    will provide you best service in qa testing services
    Design Services and Colan Infotech has a group of exceedingly dedicated, inventive and creative experts with an energy for delivering exciting ,
    helpful and stylish Web and Mobile Applications, We are one of the best software testing services company
    and of course we stepped in bangalore too

  • Vaibhaw Anand

    getting error when i add ‘ngCordova’ in app.js file.
    i have followed all the steps as mentioned by you.