Sample App using the PhoneGap Database API

This is the third version of my Employee Directory application. The jQuery Mobile and the Mobile jQuery without jQuery Mobile versions both used JSON services to get data from a remote server. In this version, the application gets data from a local database using the PhoneGap database API. As a result, this version can work offline which is probably what you would expect for this type of application.

Source code

You can download the source code here.

The database is created when you start your application. The SQL statements to create and populate the database are in employeelist.js. In a real life application, you would want to abstract that a little more.

118 Responses to Sample App using the PhoneGap Database API

  1. Sean Moore October 19, 2011 at 4:27 pm #

    Hey Christophe,

    Thanks a ton for the demo app and source code!!

    What IDE did you use to write this application?

    Kind regards,

    Sean

  2. Christophe Coenraets October 19, 2011 at 4:32 pm #

    Hi Sean,
    I used Xcode in this case, mostly to be able to quickly test on iOS devices.
    Christophe

    • stanley January 27, 2012 at 4:28 am #

      but when i put this files in the www directory,it does not load the images. it only works when am on internet and the url is set to point to your site. what steps can i follow in order to make it run locally-offline. may be there is a step that i dont know.

    • Hermann November 28, 2013 at 2:10 pm #

      Hi Mr Coenraets !
      I would like firt to thant U for this great tuto.
      I ‘ve learned much with it and I try to follow each step.
      I have a problem but google doesn’t help me.
      My application is about to display a list from mysql data base using ajax and jquery.
      whenever I land on the list.html, I need to refrech the page before I get the data displayed. Is there any way to diplay the list without refresh the page since after the build in phonegap, there won’t be any refrech button.
      Thank for helping the newbie.

  3. Sean Moore October 20, 2011 at 6:10 am #

    Hi Christophe,

    Ok, great. Thanks for the info! Greatly appreciated!

    Sean

  4. iPhone App Development October 24, 2011 at 10:57 am #

    Nice Share, It will open a window for the beginners.

  5. Xybrek October 26, 2011 at 8:03 am #

    I wonder why when I load this on my phonegap android project (Froyo) the list does not show up, only the header bars. Am I missing something?

    • alvin April 24, 2012 at 10:50 am #

      Hi Xybreak, I have solved the question. You have to check with your phonegap version. I am using phonegap 1.6.1, the file “phonegap.js” mentioned inside this example is no longer exist. So please check the

      to

      • mano July 4, 2012 at 12:22 pm #

        HI alvin, Did you changed the full phonegap.js file? when i change itto 1.8.0 its not working

        • anudeep July 5, 2012 at 6:41 pm #

          hi mano,
          i changed the phonegap.js file to cordova-1.5.5 nw its working fine for me…

          • Aniket February 14, 2014 at 5:31 am #

            Can you please be a little more specific about the cordova-1.5.5 file? Where can I find it?

  6. Sampath October 27, 2011 at 11:09 am #

    Hi Christophe,
    Iam new to Phonegap and jquery.Thanks for the demo app, this will help me get started.But when I load this on my phonegap android project (Froyo) the list does not show up, only the header bars.Could you please help me on this.

    Thanks,
    Sampath

    • chanakya January 10, 2012 at 9:14 am #

      hey have u got ur error resolved…i;m facing the same…..let me know the solution….

    • iphone.developer17@gmail.com July 10, 2012 at 9:43 am #

      Have you solved this issue ???
      I am facing same problem !!

  7. Upworks October 31, 2011 at 6:11 pm #

    Hi Christophe, Are you using a build script to minify and package the www folder in the examples?

  8. blestab November 2, 2011 at 6:19 am #

    Hi Chris,

    Any chance of a step-by-step article / tutorial on this. I am a complete noobie to app development.

    Thanks

  9. Vladimir November 5, 2011 at 7:49 pm #

    Trying to build in MacSO lion for iOS and got the following error:

    /Users/tomato_elephant/Documents/DW_NAF/PhoneGapLib/Classes/Camera.m:178:13: error: type of property ‘returnType’ (‘unsigned int’) does not match type of ivar ‘returnType’ (‘enum DestinationType’) [3]
    @synthesize returnType;
    ^
    /Users/tomato_elephant/Documents/DW_NAF/PhoneGapLib/Classes/Camera.h:25:23: note: ivar is declared here [3]
    enum DestinationType returnType;

  10. Tom November 15, 2011 at 7:40 pm #

    Same error here since I downloaded the new SDK and upgraded to Phonegap 1.2 (I’m using Dreamweaver CS5.5 to build)

    error: type of property ‘returnType’ (‘unsigned int’) does not match type of ivar ‘returnType’ (‘enum DestinationType’) [3]
    @synthesize returnType;
    ^
    /Users/tomdevlin/Documents/DW_NAF/PhoneGapLib/Classes/Camera.h:25:23: note: ivar is declared here [3]
    enum DestinationType returnType;
    ^
    1 error generated.

  11. Farfayus November 17, 2011 at 11:09 am #

    like Tom :
    Same error here since I downloaded the new SDK and upgraded to Phonegap 1.2 (I’m using Dreamweaver CS5.5 to build)

    error: type of property ‘returnType’ (‘unsigned int’) does not match type of ivar ‘returnType’ (‘enum DestinationType’) [3]
    @synthesize returnType;
    ^
    /Users/tomdevlin/Documents/DW_NAF/PhoneGapLib/Classes/Camera.h:25:23: note: ivar is declared here [3]
    enum DestinationType returnType;
    ^
    1 error generated.

    but no error if i compile and simulate from xcode and phonegap… only in DW… so the android compilation dont have error to.. only with IOS

  12. bütün gazeteler November 29, 2011 at 9:40 am #

    Thanks for a successful application. The best iPhone applications http://www.ntvmsnbc.com/id/25016381/

  13. kiranatama November 30, 2011 at 12:16 am #

    I have same error.. can anybody fix that.. thanks for reply

  14. tbrand November 30, 2011 at 8:52 am #

    Hello. I am also getting this same error using Dreamweaver 5.5 to build.

    error: type of property ‘returnType’ (‘unsigned int’) does not match type of ivar ‘returnType’ (‘enum DestinationType’) [3]
    @synthesize returnType;
    ^
    /Users/name/Documents/DW_NAF/PhoneGapLib/Classes/Camera.h:25:23: note: ivar is declared here [3]
    enum DestinationType returnType;
    ^
    1 error generated.

    Anyone figure this one out yet?

    • Andrew Gscheidle January 20, 2012 at 5:57 am #

      I fixed the above error by opening the class mentioned, finding the var declaration mentioned, and adding “enum” prefix before it. Compiled then without errors.

  15. Adewale George December 6, 2011 at 3:11 pm #

    Thanks for sharing..
    really Inspiring

  16. erasmus kratos January 11, 2012 at 6:21 am #

    can we use sqlite for an alternative local storage here?

  17. Ralph January 20, 2012 at 7:12 pm #

    Dear Christophe. Thanks a lot for this great stuff. Exactly what I needed and could not find in the jqm forum.
    Now, I want to do my own data driven application but simpler. But I am struggling…

    My application has only a link list and a detail-page. So I don’t need the count bubbles in the list. On the detail page, I also don’t need the link “View Manager”.

    How can I remove those two functions:
    “from species e left join species r on r.managerId = e.id ” +
    and
    ” + species.reportCount + ‘‘);
    (in employeelist.js)?

    Thanks in advance for your support!

  18. Ralph January 20, 2012 at 7:18 pm #

    I forgot… Also don’t need “Direct Report”.

  19. Ralph January 20, 2012 at 7:37 pm #

    And another question…
    From where does reportCount get the number? John Williams reports to Paula Gates, Paul Jones and Steven Wells. In the database is only an entry for the Manager. Where is the information stored to who the person has to report (if applicable)?

  20. Russell January 22, 2012 at 2:16 am #

    Thanks Christophe! This example is awesome. I’ve decided to learn some new skills, and I think it’s easiest to dig into code and figure out how it works. I’ve figured out pretty much everything, except the getEmployee(tx) function. I’m wondering if you would mind walking through what it’s doing?

    I’m assuming they are variable containers, but I’m confused by why they use “e” instead of “employee” (i.e. e.firstName instead of employee.firstName)

    Thanks again! It’s been fun playing around with this.

    • Russell January 22, 2012 at 3:21 am #

      So I looked at this a bit more and I figured it out, but is there a reason why you don’t just run the SELECT FROM GROUP BY ORDER BY commands directly in the tx.executeSql string?

      i.e. tx.executeSql(SELECT * FROM employee ORDER BY etc, [], getEmployee_success);

  21. Andrew Briggs January 22, 2012 at 6:01 pm #

    To everyone having problems getting it running on Android, this app comes with the iOS version of PhoneGap – you need to swap js/phonegap.js for the Android version to get it to run correctly.

    Thanks for the code Christophe!

    • agdish February 12, 2012 at 5:18 pm #

      doesn’t not resolve the problem

  22. Celso Soares January 29, 2012 at 7:36 pm #

    Thanks for sharing this app! Please keep them phonegap apps and demos coming!
    I’ve got mapkit covered, so maybe something that uses the camera?

  23. Silvester February 5, 2012 at 2:53 pm #

    I just changed jQuery with zepto.js and it works perfect. I think it works even faster than jquery.

    Lp. Silvester

    • Silvester February 6, 2012 at 10:54 am #

      An odd behavior, it works fine on android 2.3 but not in 2.1. There are some differences in the sql, because of the join you loose data in android 2.1. But I have no idea where to look on android documentation for changes in DB.

      Lp. Silvester

      • Silvester February 6, 2012 at 5:09 pm #

        Again me, sorted out what’s wrong. In this way it is backwards compatiple with Android 2.1.
        Change the sql’s ex.:
        var sql = “select e.id id, e.firstName firstName, e.lastName lastName, e.title title, e.picture picture, count(r.id) reportCount ” + “from employee e left join employee r on r.managerId = e.id ” + “group by e.id order by e.lastName, e.firstName”;

        Lp. Silvester

    • agdish February 12, 2012 at 5:19 pm #

      how do you do this

  24. The Beast February 8, 2012 at 11:49 am #

    The code is not correct… dbCreated is always false and the idea is not like that…

  25. agdish February 12, 2012 at 5:21 pm #

    have some body qet it to work??????????????????????????????????

  26. Giancarlo February 23, 2012 at 3:04 pm #

    It’s possible mix your 2 sample (database and json) for create an app that:
    load json in background and populate db.
    In this way, the application would work both online and offline

  27. carsanjay March 3, 2012 at 7:16 pm #

    thanks for sharing, i have same problem

  28. MIGUEL ANGEL March 9, 2012 at 7:20 pm #

    Hi everybody, I could fix it. The problem is the event document.addEventListener for “deviceready” doesn’t fire. I tried fix it with new “Cordova” Phonegap but it was a waste of time.

    To fix it, you can remove every “document.addEventListener(“deviceready”, onDeviceReady, false)” line in employeedetails.js, employeelist.js and reportlist.js files; and add after a onDeviceReady(); (or even a setTimeOut):
    //document.addEventListener(“deviceready”, onDeviceReady, false);
    onDeviceReady(); // <== Fixed line!

    Thank you to Christofe por his awesome job and his Web.

    • Ferris G March 29, 2012 at 11:39 pm #

      For running it on the desktop (I ran it on my Safari/Mac), I changed the above line (mentioned by MIGUEL ANGEL) to:

      $(document).ready(function() { onDeviceReady(); });

      Since there’s no Phoegap.js file for mac, I did not swap the phonegap.js file. I assumed since the functionality used is simply the storage (no camera, etc..), it should work fine using the phonegap.js for iOS which Christophe included, and it sure did work.

      • Javier Vila October 9, 2012 at 9:45 am #

        :):):):)
        It´s OK!!!!!!!!!!!!!
        Thanks a lot!

      • fakhrulzakry May 20, 2013 at 1:58 pm #

        OMG! its worked!! THANK YOU SO MUCHHH

      • bryly June 27, 2013 at 1:50 pm #

        Commenting out the line worked great. Thanks for the tip.

    • nono May 3, 2012 at 12:39 pm #

      Hey, that worked! Thanks a lot!

  29. STeven March 13, 2012 at 8:51 pm #

    Grea8 Stuff, your tutorial are so detailed and i like the evolution, perfect for beginners. Big Thank’s

  30. Bertho March 14, 2012 at 7:59 am #

    Hey Christophe,
    Thanks for your sharing.
    I Want to ask you, Examples of applications that you provide only to read from the database, can you help me make an example: insert, delete, update? I mean CRUD.
    Also the login -logout. Multi user logic . So every user who can login to read the data online with the help of php on the server and json.
    Thanks for help.

  31. Trond March 19, 2012 at 10:17 am #

    Hi! I got some problems with my app using eclipse on windows. I have changed the phonegap.js to android version, and I get the program running. The problem is when I click on any of the employees, I get the following error message: “A network error has occured (file: ///android_asset/www/employeedetails.html?id=10)”
    Anybody got a solution for that?
    I just pasted the whole project from a guy that runs eclipse on mac, and he doesn’t have this problem….

  32. Valter Vicente March 19, 2012 at 10:34 am #

    @Christophe – Thanks for all the code and the effort! You rock!

    @Andrew Briggs – Thanks for make me realize that I needed to switch the js from iPhone to the Android one, to make it work!

    @Miguel Angel – That was the final working code to make all this work. Thanks!

  33. Abiodun March 20, 2012 at 2:13 pm #

    Can you please do a video screen cast explaining .js files and and how to integrate into Database for a beginner? Thanks

  34. NAveed March 21, 2012 at 8:20 am #

    good stuff, keep it up

  35. Phonegapfanboy March 22, 2012 at 5:39 pm #

    Great job, Chris. A question regarding the DB design. It seems that every time this application starts, the database will be re-created, right? In real life, you don’t want to do that but keep a static DB and just to initialize it once. What is your best practice for this?

  36. Arivu Selvan March 23, 2012 at 4:59 am #

    thanks ……….wonderful work i want more like these sample application.

  37. Josbe March 28, 2012 at 12:11 pm #

    Could you post a tutorial how to combine these json and db apps in orded to make an app that loads the data from external server and populates database with that data. I would want to make an app that works both offline and online?

  38. hoangduc April 11, 2012 at 11:49 pm #

    hi.
    when I click on any of the employees, I get the following error message: “A network error has occured (file: ///android_asset/www/employeedetails.html?id=7)”

  39. hoangduc April 11, 2012 at 11:50 pm #

    hi.
    when I click on any of the employees, I get the following error message: “A network error has occured (file: ///android_asset/www/employeedetails.html?id=17)”

  40. Akshay Thakur April 13, 2012 at 7:02 am #

    Hi Christhphe,

    Thank you for sharing it. Helped a lot. :)

    Regards
    Akshay

  41. Vivek April 16, 2012 at 5:00 pm #

    How do you add a search filter for this using jquery mobile?

  42. Patricio April 22, 2012 at 8:20 pm #

    I have the same problem when i click any of the employees.
    Any solution to the “A network error has occured (file: ///android_asset/www/employeedetails.html?id=7)” problem?

  43. Geetha April 25, 2012 at 10:27 am #

    Hi,how the employee details from local database is working,for me i can see only 2 bars,one is showing title like Employee Directory and another is showing Employee List.Help is appreciated.

  44. Nandakishore May 16, 2012 at 8:51 am #

    Excellent example. Thanks a lot… helped me lot :-)

  45. eskanndar May 19, 2012 at 12:55 pm #

    Do you have a version of Employees apps with offline AND server synchronizable data?

  46. Adam May 24, 2012 at 3:54 am #

    Hi,

    This is awesome! Thanks for sharing.

    I downloaded the files and want to try and get it set up on my machine so I can play and learn. However, when I run it in the simulator I only get the word ‘Employee List’ appearing – no javascript or any other data. Was wondering if you could help me out?

    Thanks!

    • Adam May 25, 2012 at 2:34 am #

      I think I figured it out – I had Cordova running, not PhoneGap

  47. Argent Ounce May 30, 2012 at 7:31 am #

    Thanks for taking the time to make and share this. Very useful!

  48. andres June 7, 2012 at 7:40 pm #

    please help i have this error i dont know how to fix it

    Error: executing module function ‘setInfo’ in module ‘cordova/plugin/ios/device’. Have you included the iOS version of the cordova-1.7.0.js file?

  49. Jiten Oswal June 12, 2012 at 11:26 am #

    The app is not working. I guess there have been alot of changes in phonegap since the time this app was made. Author please update the post or please remove it .. bcoz people are getting stuck here and we dont even know how to fix them .. everyone is stuck half way. :(

  50. Carlos Lopez June 20, 2012 at 5:51 pm #

    I am proving it in an Android (Galaxy II) and it does not generate the database, actually when I use the file phonegap.js me there does not work the application, the version of the web services if that me works well. For that it can be? Thank you

  51. Alex June 25, 2012 at 9:11 am #

    What is this App doing? There’s no list, only the Toolbars…?

  52. asdd June 27, 2012 at 9:33 am #

    wts der to ask

  53. vishal June 27, 2012 at 10:08 am #

    I have taken the sample and using it…but it is only listing employee ..when i click on employee it gives me error network error occured file:///android_asset/www/emplyeedetails.html?id=10

  54. Iphony July 10, 2012 at 9:49 am #

    Hi Christhphe,

    I am unable to fetch list.
    Headers are appearing but i didn’t find any way to get list !!

  55. Pablo July 10, 2012 at 9:27 pm #

    Hello

    I am developing an application on PhoneGap and will have access to databases. I wanted to know how to handle the maximum size allowed for the database and if there is any better alternative?

    thanks

  56. Khushboo July 12, 2012 at 9:36 am #

    Hello..m using da code for android.. but there is error in jquery.js file.. Plz tel how to resolve it..

  57. Jerry Fernandez July 30, 2012 at 6:58 pm #

    Thanks a lot it worked for me.. I never knew even I could make apps :)

  58. sabrito August 13, 2012 at 1:11 pm #

    hello,
    i’m a beginner with (Html5 and js). I’m trynig to test this application with Visual Studio 2010 and PhoneGap 2.0 and when I execute this the list does not show up, only the header bars. Am I missing something? how can i know if Db was created ???

  59. Mahdi August 17, 2012 at 12:31 am #

    What is this App doing? There’s no list, only the Toolbars…?

  60. José August 23, 2012 at 10:49 pm #

    Hola, muy interesante tu aplicación, quisiera saber si tienes algún manual o que me recomiendas para poder hacer la conexión a base de datos remota desde una aplicación nativa para móviles

  61. rikoy September 2, 2012 at 9:40 am #

    please, can you share the database?

  62. rikoy September 3, 2012 at 11:15 am #

    is this only work on iPhone?

  63. Arnold Babasa September 13, 2012 at 9:53 am #

    Hi!! Thank you very much for this interesting tutorial. I am new to develping apps using Phonegap. I just have one question. When it comes to populating the db with populateDB(), is there a way in which you can tell the app to sync it’s data with that of a remote database? How can you tell if the table exists and then you call another function that fetches this data? Thank you!

  64. André September 30, 2012 at 6:18 pm #

    I wod like to know if you could post an application with these ting and more jquery mobile

  65. Kenan October 10, 2012 at 10:19 am #

    Why does the application populate the database every time i turn off the simulator?
    I am using iOS simulator 5.1 with Xcode 4.5 and phonegap 2.1.0

    • Kenan October 10, 2012 at 10:21 am #

      Meaning it never saves the data to a local file, and the getEmployees method never get’s executed

  66. Berguiga October 17, 2012 at 10:01 am #

    My problem display on dreamweaver occur android emulator but I do not list the use

  67. Web Design Group October 18, 2012 at 5:22 pm #

    The database calls were useful to me. Learning about PhoneGap is proving to be a challenge.

  68. abayomi October 21, 2012 at 11:56 pm #

    Hello there.I pray someone out there respond to my comment urgently.This is an urgent SOS. Thank you for your blog and for taking out time to impact knowledge.However,I appreciate your employee directory with phone gap api for local storage-it has helped in my understanding of the subject.I came accross a problem recently cos I was trying to insert into my database in my local language with this text(Odò kan si ti Edeni ṣàn wá lati rin ọgbà na; lati ibẹ̀ li o gbé yà, o si di ipa ori mẹrin. ) but on display the result after select query gave was different(Odò kan si ti Edeni ṣà n wá lati rin á»gbà n…).Can you help.How do I get the exact text I inserted in the database.

  69. Mike Judkins October 27, 2012 at 9:49 pm #

    Code doesn’t work for me with iOS 6. I just get the Employee Directory header and Employee List title, no results. I’m using the Phonegap build service, which should correctly generate the version of phonegap.js. Code must be out dated already.

  70. senthil October 30, 2012 at 11:16 am #

    Thanks for posting the source code for phonegap. It is not working for me for Android, when run I get this error:
    10-30 16:44:09.390: E/Web Console(638): Uncaught ReferenceError: cordova is not defined at null:1

    Please help.
    Senthil

  71. Rui November 16, 2012 at 11:30 pm #

    congrats for the source code… i´m new to phonegap, i supose you´re using Sqlite database right? im kinda struggling trying to find a way to use a sqlite database, i now that we can access database with phonegap plugin, but can you provide some info about the you did that, did you use localstorage or somthing?´
    Thanks!

  72. Zaib December 14, 2012 at 8:06 pm #

    How db will work .. for me it works but no data is there just theme showing .. please can you tell me how to show the data…

  73. sohbet odalari December 21, 2012 at 12:12 am #

    karakoki thnakss

  74. airfel kombi servis January 5, 2013 at 1:36 pm #

    thank you so much

  75. Arturo January 11, 2013 at 10:16 pm #

    Hi, Thanks this is just what i need but i downloaded the project and it doesnt have an xcode project to run it is just the html, css and javascript files, im still a noob on phonegap so is probably something silly but i would apprecieate the help!

  76. Manoj Damkondwar January 16, 2013 at 6:52 pm #

    thanks from heart, what examples you have given can i use for commercial..

  77. speedy March 20, 2013 at 11:58 am #

    Nice Demo !!! thanks a lot :D

  78. Dhruv R Thaker March 25, 2013 at 5:56 am #

    Looking for more knowlege in phonegap. Which is best and affordable option for accepting payment.

  79. Aneesh Dogra March 25, 2013 at 4:49 pm #

    This is for the people for whom “onDeviceReady” doesn’t get executed. Its most probably because you are using different versions of Phonegap and Cordova. The project uses cordova 1.1 while the latest Phonegap and Cordova version is 2.5. So, most of you guys will be testing this app on 2.5. Here’s how to fix it:

    Replace www/js/phonegap.js with the cordova-VERSION.js, where VERSION is your phonegap’s version.

    • Magesh April 2, 2013 at 12:27 pm #

      Good Tutorial thank you so much..

  80. Thirion May 7, 2013 at 3:35 am #

    To get this working properly, I had to do the following:
    Install Android SDK
    Download Cordova 2.6.0 (I used the prebuilt PhoneGap download of same version)
    Install Chrome browser.
    Install Ripple Emulator inside the chrome browser. (from chrome web store)
    Install NetBeans 7.3
    Install AndroidNB plugin for NetBeans (http://www.nbandroid.org)

    I used Cordova command line to create initial project.
    Copy the source from this demo project into the ‘www’ folder.
    Use NetBeans to create an HTML5 project from existing sources and use the www folder as the Site Root. I rename the project from ‘assets’ to something more relevant while keeping the project directory as ‘assets’.

    What this gives me is an environment where I can run and debug the web portion of the app in Chrome with the NetBeans debugger attached. (click on www folder and then Run)
    This allows me to set breakpoints in the javascript files in NetBeans. When the browser execution gets to the breakpoint, control is transferred to NetBeans where you can inspect the values of variables, step through code etc.

    If you enable the Ripple Emulator for the site, you will see a phone skin which you can rotate, shake, emulate gps co-ordinates etc. The example of this demo app works as is if you set the Cordova version to 1.0.0 in Ripple.

    If you click on the project root inside NetBeans and click Run, it will be seen as an Android project and allow you to run it on an Android Virtual Device, or an actual phone that’s plugged in via USB.

    Normally NetBeans will show an Icon for Web app projects, but since I nested an HTML5 project inside an Android project, and opened the Android project in NetBeans, we only see the Android Icon on the project root, and not the HTML5 icon on the www folder as well. To see the HTML5 icon for the embedded web project, click on the Files tab.

    I removed the phonegap js file and replaced it with Cordova-2.6.0.js file and changed all references. Now you can change the Cordova version in the Ripple Emulator to 2.0.0.

    If you run this in the browser without ripple, then some of the comments above allow the onDeviceReady to be called by replacing
    document.addEventListener(“deviceready”, onDeviceReady, false);
    with:
    $(document).ready(function() {
    onDeviceReady();
    }

    BUT with the ripple emulator enabled, that is not necessary. It actually gives other errors when using an actual phone. When document ready function is called, Cordova isn’t loaded yet, so creating the db connection fails.

    To get it to work in the browser with or without an emulator and on an actual device, you can use this:

    $(document).ready(function() {
    // are we running in native app or in browser?
    window.isPhone = false;
    if(document.URL.indexOf(“http://”) === -1) {
    window.isPhone = true;
    }

    if(window.isPhone) {
    //alert(‘isPhone’);
    document.addEventListener(“deviceready”, onDeviceReady, false);
    } else {
    //alert(‘isBrowser’);
    onDeviceReady();
    }
    });

    NOTE: when using chrome without the emulator, onDeviceReady gets called once (with isBrowser alert if not commented out). When using the emulator, it gets called twice. I assume that’s because the emulator calls the document ready function as well. When running on a physical device, it only gets called once (with alert isPhone if not commented out).

    One other thing that I’ve realized is that the db.transaction method that takes a success condition is fired concurrently with the db.transaction! So to get it to work I changed:
    db.transaction(populateDB, transaction_error, populateDB_success);
    inside employeelist.js to just be:
    db.transaction(populateDB, transaction_error);
    and then added this to the end of the populateDB(tx) function:
    populateDB_success();

    I don’t know how to add an attachment here, otherwise I’ll be happy to give anyone the zip of my project folder.

    Hope it helps anyone who is also getting started with HTML5, Android and Cordova.

  81. Sydney Van da Seide May 19, 2013 at 2:13 am #

    Hey guys,
    i downloaded the example for phonegap with the local database.

    If i try to test the sample with phonegap build the application starts but the local database was not create. I test it on android devices.

    Have anybody an idea how it works correctly?

  82. Goni July 10, 2013 at 11:30 am #

    To bring this apps put cordova.js instead of phonegap.js, update yous references in all html files.

  83. jecky August 11, 2013 at 12:53 pm #

    thanks you , tutorial is nice :D

  84. Anupama August 23, 2013 at 6:13 am #

    Hi Christophe,

    Thank you for sharing this… Its Great!!!!!

  85. Miguel August 27, 2013 at 6:41 pm #

    Hello Man thanks so much for the tutorial i’m sorry if my english is not perfect.
    I have a little question
    when i use the function populateDB() but sending the data with Jquery it’s save good.
    but when i destroy the app and open again the data is lose.

    i use the very same structure that you use in your example.
    may be i’m doing some thing rong. this is my code.

    var db;
    var dbCreated = false;

    document.addEventListener(“deviceready”, onDeviceReady, false);

    function onDeviceReady()
    {
    alert(“Cordova listo!!”);

    $(‘#guardar’).click(function(){
    alert(“llega al clic!!”);
    if($(‘#nombre’).val().length > 0)
    {
    if($(‘#telefono’).val().length > 0)
    {
    db = window.openDatabase(“DataBasePrueba”, “1.0″, “PhoneGap Demo”, 200000);
    db.transaction(populateDB, transaction_error, populateDB_success);
    }
    else
    {
    alert(“Debe ingresar su numero de telefono”);
    }
    }
    else
    {
    alert(‘Debe ingresar su nombre’);
    }
    });
    }

    function transaction_error(tx, error) {
    alert(“Database Error: ” + error + ” tx: ” + tx);
    }

    function populateDB_success() {
    dbCreated = true;
    //db.transaction(getEmployees, transaction_error);
    alert(‘Registro guardado correctamente’);
    }

    function populateDB(tx) {

    //tx.executeSql(‘DROP TABLE IF EXISTS ejemplo’);
    var sql =
    “CREATE TABLE IF NOT EXISTS ejemplo ( “+
    “nombre VARCHAR(50),” +
    “telefono INTEGER(10));”;
    tx.executeSql(sql);

    tx.executeSql(“INSERT INTO ejemplo (nombre,telefono) VALUES (‘”+ $(“#nombre”).val() +”‘,’”+ $(“#telefono”).val() +”‘);”);
    }

  86. Mohamed November 4, 2013 at 9:35 pm #

    Thank you so much for sharing this. I would like to create a dictionary app. Can I use your sample app to achieve my goal?

    Thanks again!

  87. sprsrini November 10, 2013 at 2:16 am #

    I have my own employees.db created and how to import it into the program ?
    Help will be appreciated.

  88. Eduardo February 17, 2014 at 7:13 pm #

    Hola que tal, excelente el tuto… la verdad yo soy nuevo en phonegap y justamente he hecho app en las que creo la base de datos en un .js creando e insertando campos dentro de una tabla y mi consulta es. ¿Como puedo colocar una base de datos sqlite precargada con toda la informacion hecho con sqlitebrowser dentro de mi aplicativo?. por favor me podrias sugerir algo o una pagina que me indice como realizarlo. gracias

Trackbacks/Pingbacks

  1. Sample Application using jQuery Mobile and PhoneGap - October 19, 2011

    [...] version of the same application getting data from a local database using the PhoneGap database api here. Filed Under: JQuery, JQuery Mobile, [...]

  2. Sample App using the PhoneGap Database API | industry, blog, iphone, app, creative, games, programming, project, various, criminalminds - October 20, 2011

    [...] more from the original source: Sample App using the PhoneGap Database API employee, employee-directory, get-data, json, Mobile, query-mobile, [...]

  3. PowenKo > PKML < PhoneGap | PowenKo 柯博文 - January 25, 2012

    [...] http://coenraets.org/blog/2011/10/sample-app-using-the-phonegap-database-api/ [...]

  4. Aplicación de ejemplo usando jQuery Mobile y PhoneGap « desarrollophpsenior - March 22, 2012

    [...] I posted a version of the same application getting data from a local database using the PhoneGap database api here. [...]

  5. PhoneGap – migrating iOS applications to Android (Part 1) | Do it yourself Android - April 6, 2012

    [...] second sample is an Employee Directory application using using the PhoneGap Database API. It is created by Christophe Coenraets. Please checkout his blog for a lot of interesting posts on [...]

  6. Un completo ejemplo de Phonegap, jQueryMobile, PHP, MySQL, JSon… | Programación de Dispositivos Móviles - June 17, 2013

    [...] I posted a version of the same application getting data from a local database using the PhoneGap database api here. [...]

  7. Un completo ejemplo de Phonegap, jQueryMobile, PHP, MySQL, JSon… | Centro Inca - March 28, 2014

    […] I posted a version of the same application getting data from a local database using the PhoneGap database api here. […]

  8. Phonegap for Android JSCallback error meaning OnDeviceReady not called | MSDLT Blog - April 10, 2014

    […] for hours last night while trying to migrate this great example app Sample App using the PhoneGap Database API to work on Android using Eclipse and an Android emulator. Everything was going well until I tried […]

Leave a Reply