Introduction to PhoneGap
Background
Setting up the environment for Android
Handling Events
Working With The Device, The Network, And Notifications
Getting Information from the Device
Determining the Connection Type
Using Notifications
Using Alerts
Using Confirmation Dialogs
Using Beeps
Using Vibrations
Accelerometer
Using the Acceleration Object
Using Accelerometer Methods
Media
The Media Object
Using Media Methods
Camera
Using The Camera Object
Using The Getpicture Method
Using Camera Options
Geolocation
Position, PositionError, Coord
Geolocation Methods
Geolocation Options
Deployment using Phonegap (Android)
Hands-on exercises
Storage
Available options
Db object
localStorage
Files
Filessystem
File read & write
Handling errors
Contacts
Creating contacts
Finding contacts
Handling errors
Capture
Video
Audio
Handling errors
Hands-on exercises
2. Introduction to PhoneGap
Background
Setting up the environment for Android
Handling Events
Working With The Device, The Network, And Notifications
Getting Information from the Device
Determining the Connection Type
Using Notifications
Using Alerts
Using Confirmation Dialogs
Using Beeps
Using Vibrations
Accelerometer
Using the Acceleration Object
Using Accelerometer Methods
Media
The Media Object
Using Media Methods
Camera
Using The Camera Object
Using The Getpicture Method
Using Camera Options
Geolocation
Position, PositionError, Coord
Geolocation Methods
Geolocation Options
Deployment using Phonegap (Android)
Hands-on exercises
3. Introduction to PhoneGap
•To develop apps using PhoneGap, the developer does not require to have knowledge of mobile programming language but only web-development languages like, HTML, CSS, and JScript.
4. Introduction to PhoneGap
•To develop apps using PhoneGap, the developer does not require to have knowledge of mobile programming language but only web-development languages like, HTML, CSS, and JScript.
5. Introduction to PhoneGap
• PhoneGap produces apps for all popular mobile OS platforms such as iOS, Android, BlackBerry, and Windows Mobile OS etc
6. Prerequisites
•It is mandatory that you have knowledge of HTML, CSS and JScript to create website that you might want to put on App.
•No other programming language is required to use PhoneGap.
7. Introduction of Phonegap
•Mobile, handhelds and easy-to-carry devices have started a new revolution in software engineering.
8. Introduction of Phonegap
•These small but efficient devices are capable to run applications created with high-end programming languages.
9. PhoneGap Architecture
•The architecture of a mobile device is similar to that of a computer system.
•It has custom built hardware, firmware, and operating systems.
11. PhoneGap Architecture
•These three items are mostly proprietary and are engineered, developed, and assembled under one flagship organization.
12. PhoneGap Architecture
•Apps (Application Software) are developed both by flagship organization and developers from outside the organization.
13. PhoneGap Architecture
•A number of well-recognized mobile operating systems are available in the market in both proprietary and open-source categories. Most widely used mobile operating systems are:
–Android
–IOS
–BlackBerry
–Windows
14.
15. PhoneGap
•PhoneGap may be seen as a solution to all problems mentioned above.
•PhoneGap is a framework that makes the developers develop their apps using standard web APIs for all major mobile operating systems.
•It is open-source and free
16. PhoneGap
•Developers only need to know web development using HTML, CSS and JavaScript.
•PhoneGap takes care of rest of the work, such as look and feel of the app and portability among various mobile OS.
18. PhoneGap
•Using PhoneGap, one can create apps for all major mobile OSl like Apple iOS, Android, BlackBerry, Windows etc.
•This does not require the developer to have expertise over any of the above mentioned platforms neither the developer is required to know programming to code the app from scratch
19. PhoneGap
•PhoneGap allows its users to upload the data contents on website and it automatically converts it to various App files.
•In this tutorial, we shall see how to create app for apple, android, and windows platform online and without using any offline tool.
20. PhoneGap
•Though PhoneGap supports offline creation of apps using cordova command line interface and Github repository mechanism but we shall concentrate on minimum effort procedure.
21. PhoneGap
•We assume that you are well versed with web technologies and have your web application ready to be shipped as an app.
•Because PhoneGap supports only HTML, CSS and JavaScript, it is mandatory that the application should be created using these technologies only.
22. PhoneGap
•From developers perspective, an app should have the following items included in its package:
–Configuration files
–Icons for app
–Information or content (built using web- technologies)
23. Configuration
•Our web app will need only one configuration file that should be adequate to configure all its necessary settings.
•Its name is config.xml.
•This file contains all the necessary information required to compile the app.
24. config.xml
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns = "http://www.w3.org/ns/widgets"
xmlns:gap = "http://phonegap.com/ns/1.0"
id = "com.tutorialspoint.onlineviewer"
version = "1.0">
<name>Tutorials Point</name>
<description>
Tutorials Point Online Viewer
</description>
<author href="http://tutorialspoint.com" email="contact@tutorialspoint.com">
Tutorials Point
</author>
27. config.xml
•All configuration contents are wrapped in <widget> tag. Brief description of these is as follows:
<widget id = ”app_id”>
•id is your reserved app-id on various app stores. It is in reverse-domain name style i.e. com.hp.phonegap.tutorial etc.
<widget version = "x.y.z">
28. config.xml
<name> App Name</name>
•This is name of app, which will be displayed below app icon on mobile screen. Your app can be searched using this name.
29. config.xml
•This is a brief description of what is the app about, and what it is.
<description> My First Web App </description>
30. config.xml
•This field contains name of the creator or programmer, generally set to the name of organization which is launching this app.
<author> Author_Name </author>
35. deviceready
<!DOCTYPE html> <html> <head> <title>Device Ready Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { // Now safe to use device APIs } </script> </head> <body onload="onLoad()"> </body> </html>
36. pause
document.addEventListener("pause", yourCallbackFunction, false);
•The pause event fires when the native platform puts the application into the background, typically when the user switches to a different application.
•Applications typically should use document.addEventListener to attach an event listener once the deviceready event fires
37. pause
<!DOCTYPE html> <html> <head> <title>Pause Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { document.addEventListener("pause", onPause, false); } // Handle the pause event // function onPause() { } </script> </head> <body onload="onLoad()"> </body> </html>
38. resume
document.addEventListener("resume", yourCallbackFunction, false);
•The resume event fires when the native platform pulls the application out from the background.
•Applications typically should use document.addEventListener to attach an event listener once the deviceready event fires.
39. resume
<!DOCTYPE html> <html> <head> <title>Resume Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { document.addEventListener("resume", onResume, false); } // Handle the resume event // function onResume() { } </script> </head> <body onload="onLoad()"> </body> </html>
40. backbutton
document.addEventListener("backbutton", yourCallbackFunction, false);
•To override the default back-button behavior, register an event listener for the backbutton event, typically by calling document.addEventListener once you receive the deviceready event.
•It is no longer necessary to call any other method to override the back-button behavior
41. backbutton
<!DOCTYPE html> <html> <head> <title>Back Button Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { // Register the event listener document.addEventListener("backbutton", onBackKeyDown, false); } // Handle the back button // function onBackKeyDown() { } </script> </head> <body onload="onLoad()"> </body> </html>
43. menubutton
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Menu Button Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { // Register the event listener document.addEventListener("menubutton", onMenuKeyDown, false); } // Handle the menu button // function onMenuKeyDown() { } </script> </head> <body onload="onLoad()"> </body> </html>
44. searchbutton
document.addEventListener("searchbutton", yourCallbackFunction, false);
•If you need to override the default search button behavior on Android you can register an event listener for the 'searchbutton' event.
•Applications typically should use document.addEventListener to attach an event listener once the deviceready event fires.
45. searchbutton
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Search Button Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { // Register the event listener document.addEventListener("searchbutton", onSearchKeyDown, false); } // Handle the search button // function onSearchKeyDown() { } </script> </head> <body onload="onLoad()"> </body> </html>
46. startcallbutton
•If you need to override the default start call behavior you can register an event listener for the startcallbutton event.
•Applications typically should use document.addEventListener to attach an event listener once the deviceready event fires.
document.addEventListener("startcallbutton", yourCallbackFunction, false);
47. startcallbutton
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Start Call Button Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // device APIs are available // function onDeviceReady() { // Register the event listener document.addEventListener("startcallbutton", onStartCallKeyDown, false); } // Handle the start call button // function onStartCallKeyDown() { } </script> </head> <body onload="onLoad()"> </body> </html>
49. Getting Information from the Device
•Permission required –
–<plugin name="Device" value="org.apache.cordova.Device" /> (inside app/res/xml/plugins.xml)
–<uses-permission android:name="android.permission.READ_PHONE_STATE" /> (inside Menifest file)
50. Getting Information from the Device
$('#devicename').html(device.name); $('#devicephonegap').html(device.phonegap); $('#devicplatform').html(device.platform); $('#deviceuuid').html(device.uuid); $('#deviceversion').html(device.version);
59. notification.alert
•Shows a custom alert or dialog box.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
–message: Dialog message (String)
–alertCallback: Callback to invoke when alert dialog is dismissed. (Function)
–title: Dialog title (String) (Optional, Default: "Alert")
–buttonName: Button name (String) (Optional, Default: "OK")
60. notification.alert
•Most Cordova implementations use a native dialog box for this feature.
•However, some platforms simply use the browser's alertfunction, which is typically less customizable.
61. notification.alert
// Android / BlackBerry WebWorks (OS 5.0 and higher) / iPhone / Tizen // function alertDismissed() { // do something } navigator.notification.alert( 'You are the winner!', // message alertDismissed, // callback 'Game Over', // title 'Done' // buttonName );
62. notification.alert
<!DOCTYPE html> <html> <head> <title>Notification Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { // Empty } // alert dialog dismissed function alertDismissed() { // do something } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message alertDismissed, // callback 'Game Over', // title 'Done' // buttonName ); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> </body> </html>
63. notification.confirm
•Shows a customizable confirmation dialog box.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
–message: Dialog message (String)
–confirmCallback: - Callback to invoke with index of button pressed (1, 2 or 3). (Function)
–title: Dialog title (String) (Optional, Default: "Confirm")
–buttonLabels: Comma separated string with button labels (String) (Optional, Default: "OK,Cancel")
64. notification.confirm
<!DOCTYPE html> <html> <head> <title>Notification Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { // Empty } // process the confirmation dialog result function onConfirm(buttonIndex) { alert('You selected button ' + buttonIndex); } // Show a custom confirmation dialog // function showConfirm() { navigator.notification.confirm( 'You are the winner!', // message onConfirm, // callback to invoke with index of button pressed 'Game Over', // title 'Restart,Exit' // buttonLabels ); } </script> </head> <body> <p><a href="#" onclick="showConfirm(); return false;">Show Confirm</a></p> </body> </html>
75. accelerometer.getCurrentAcceleration
•Get the current acceleration along the x, y, and z axis.
navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);
•The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current device orientation.
•The accelerometer can detect 3D movement along the x, y, and z axis.
•The acceleration is returned using the accelerometerSuccess callback function
76. accelerometer.getCurrentAcceleration
<!DOCTYPE html> <html> <head> <title>Acceleration Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { navigator.accelerometer.getCurrentAcceleration(onSuccess, onError); } // onSuccess: Get a snapshot of the current acceleration // function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + 'n' + 'Acceleration Y: ' + acceleration.y + 'n' + 'Acceleration Z: ' + acceleration.z + 'n' + 'Timestamp: ' + acceleration.timestamp + 'n'); } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } </script> </head> <body> <h1>Example</h1> <p>getCurrentAcceleration</p> </body> </html>
77. Acceleration
•Contains Accelerometer data captured at a specific point in time.
•Properties
–x: Amount of acceleration on the x-axis. (in m/s^2) (Number)
–y: Amount of acceleration on the y-axis. (in m/s^2) (Number)
–z: Amount of acceleration on the z-axis. (in m/s^2) (Number)
–timestamp: Creation timestamp in milliseconds. (DOMTimeStamp)
78. Acceleration
<!DOCTYPE html> <html> <head> <title>Acceleration Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { navigator.accelerometer.getCurrentAcceleration(onSuccess, onError); } // onSuccess: Get a snapshot of the current acceleration // function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + 'n' + 'Acceleration Y: ' + acceleration.y + 'n' + 'Acceleration Z: ' + acceleration.z + 'n' + 'Timestamp: ' + acceleration.timestamp + 'n'); } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } </script> </head> <body> <h1>Example</h1> <p>getCurrentAcceleration</p> </body> </html>
80. org.apache.cordova.media
•This plugin provides the ability to record and play back audio files on a device.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(Media);
}
82. Media
var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]);
83. Media
•src: A URI containing the audio content. (DOMString)
•mediaSuccess: (Optional) The callback that executes after a Media object has completed the current play, record, or stop action. (Function)
•mediaError: (Optional) The callback that executes if an error occurs. (Function)
•mediaStatus: (Optional) The callback that executes to indicate status changes. (Function)
84. Constants
•src: A URI containing the audio content. (DOMString)
•mediaSuccess: (Optional) The callback that executes after a Media object has completed the current play, record, or stop action. (Function)
•mediaError: (Optional) The callback that executes if an error occurs. (Function)
•mediaStatus: (Optional) The callback that executes to indicate status changes. (Function)
85. Media
•The Media object provides the ability to record and play back audio files on a device.
var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]);
86. Media
•src: A URI containing the audio content. (DOMString)
•mediaSuccess: (Optional) The callback that is invoked after a Media object has completed the current play/record or stop action. (Function)
•mediaError: (Optional) The callback that is invoked if there was an error. (Function)
•mediaStatus: (Optional) The callback that is invoked to indicate status changes. (Function)
87. Media
Constants
•The following constants are reported as the only parameter to the mediaStatus callback function.
–Media.MEDIA_NONE = 0;
–Media.MEDIA_STARTING = 1;
–Media.MEDIA_RUNNING = 2;
–Media.MEDIA_PAUSED = 3;
–Media.MEDIA_STOPPED = 4;
89. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Media Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); } // Audio player // var my_media = null; var mediaTimer = null; // Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError); // Play audio my_media.play(); // Update my_media position every second if (mediaTimer == null) { mediaTimer = setInterval(function() { // get my_media position my_media.getCurrentPosition( // success callback function(position) { if (position > -1) { setAudioPosition((position) + " sec"); } }, // error callback function(e) { console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); } ); }, 1000); } } // Pause audio // function pauseAudio() { if (my_media) { my_media.pause(); } } // Stop audio // function stopAudio() { if (my_media) { my_media.stop(); } clearInterval(mediaTimer); mediaTimer = null; } // onSuccess Callback // function onSuccess() { console.log("playAudio():Audio Success"); } // onError Callback // function onError(error) { alert('code: ' + error.code + 'n' + 'message: ' + error.message + 'n'); } // Set audio position // function setAudioPosition(position) { document.getElementById('audio_position').innerHTML = position; } </script> </head> <body> <a href="#" class="btn large" onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3');">Play Audio</a> <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a> <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a> <p id="audio_position"></p> </body> </html>
90. media.getDuration
•Returns the duration of an audio file.
media.getDuration();
• Description
•Function media.getDuration is a synchronous function that returns the duration of the audio file in seconds, if known. If the duration is unknown, a value of -1 is returned.
91. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Media Example</title> <script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for Cordova to load // document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); } // Audio player // var my_media = null; var mediaTimer = null; // Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError); // Play audio my_media.play(); // Update my_media position every second if (mediaTimer == null) { mediaTimer = setInterval(function() { // get my_media position my_media.getCurrentPosition( // success callback function(position) { if (position > -1) { setAudioPosition((position) + " sec"); } }, // error callback function(e) { console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); } ); }, 1000); } } // Pause audio // function pauseAudio() { if (my_media) { my_media.pause(); } } // Stop audio // function stopAudio() { if (my_media) { my_media.stop(); } clearInterval(mediaTimer); mediaTimer = null; } // onSuccess Callback // function onSuccess() { console.log("playAudio():Audio Success"); } // onError Callback // function onError(error) { alert('code: ' + error.code + 'n' + 'message: ' + error.message + 'n'); } // Set audio position // function setAudioPosition(position) { document.getElementById('audio_position').innerHTML = position; } </script> </head> <body> <a href="#" class="btn large" onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3');">Play Audio</a> <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a> <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a> <p id="audio_position"></p> </body> </html>
92. media.getCurrentPosition
var my_media = new Media(src, onSuccess, onError);
// Update media position every second
var mediaTimer = setInterval(function () {
// get media position
my_media.getCurrentPosition(
// success callback
function (position) {
if (position > -1) {
console.log((position) + " sec");
}
},
// error callback
function (e) {
console.log("Error getting pos=" + e);
}
);
}, 1000);
93. media.getDuration
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
// Get duration
var counter = 0;
var timerDur = setInterval(function() {
counter = counter + 100;
if (counter > 2000) {
clearInterval(timerDur);
}
var dur = my_media.getDuration();
if (dur > 0) {
clearInterval(timerDur);
document.getElementById('audio_duration').innerHTML = (dur) + " sec";
}
}, 100);
94. media.pause
/ Play audio
//
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function () { console.log("playAudio():Audio Success"); },
// error callback
function (err) { console.log("playAudio():Audio Error: " + err); }
);
// Play audio
my_media.play();
// Pause after 10 seconds
setTimeout(function () {
media.pause();
}, 10000);
}
a
95. media.play
// Play audio
//
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function () {
console.log("playAudio():Audio Success");
},
// error callback
function (err) {
console.log("playAudio():Audio Error: " + err);
}
);
// Play audio
my_media.play();
}
96. media.play
// Play audio
//
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function () {
console.log("playAudio():Audio Success");
},
// error callback
function (err) {
console.log("playAudio():Audio Error: " + err);
}
);
// Play audio
my_media.play();
}
100. Storage
•Several storage APIs are available for Cordova applications
•LocalStorage
•WebSQL
•IndexedDB
101.
102. •create a table in local android database (SQLite), retrieve and show it in listview using Jquery mobile
•The name of database will be Dummy_DB and the table will be FootballPlayer.
•The table will consist of three coloumns.
•First is ID which is auto increment, the second is Name and the last is Club.
104. add some javascript code within <head> tag
//add listener when device ready
document.addEventListener("deviceready", onDeviceReady, false);
var db = window.openDatabase("Dummy_DB", "1.0", "Just a Dummy DB", 200000); //will create database Dummy_DB or open it
//function will be called when device ready
function onDeviceReady(){
db.transaction(populateDB, errorCB, successCB);
}
//create table and insert some record
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS SoccerPlayer (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Club TEXT NOT NULL)');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Alexandre Pato", "AC Milan")');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES (“Subhajit", “Mohan Bangan")');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Van Persie", "Arsenal")');
}
//function will be called when an error occurred
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
//function will be called when process succeed
function successCB() {
alert("success!");
db.transaction(queryDB,errorCB);
}
//select all from SoccerPlayer
function queryDB(tx){
tx.executeSql('SELECT * FROM SoccerPlayer',[],querySuccess,errorCB);
}
function querySuccess(tx,result){
$('#SoccerPlayerList').empty();
$.each(result.rows,function(index){
var row = result.rows.item(index);
$('#SoccerPlayerList').append('<li><a href="#"><h3 class="ui-li-heading">'+row['Name']+'</h3><p class="ui-li-desc">Club '+row['Club']+'</p></a></li>');
});
$('#SoccerPlayerList').listview();
}
105. add some javascript code within <head> tag
This javascript code are used for connecting the app to the SQLite Database. Ok, then how this thing work ?
106. add some javascript code within <head> tag
First thing first, you’ll have to add listener when the device is ready.
Then when the device ready it create connection to the database and do the transaction.
107. add listener when device ready
//add listener when device ready
document.addEventListener("deviceready", onDeviceReady, false);
var db = window.openDatabase("Dummy_DB", "1.0", "Just a Dummy DB", 200000); //will create database Dummy_DB or open it
//function will be called when device ready
function onDeviceReady(){
db.transaction(populateDB, errorCB, successCB);
}
108. add listener when device ready
Function populateDB() run to create the table and insert some record into it.
If it failed, errorCB() function will be called, otherwise successCB() will.
109. create table and insert some record
//create table and insert some record
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS SoccerPlayer');
tx.executeSql('CREATE TABLE IF NOT EXISTS SoccerPlayer (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Club TEXT NOT NULL)');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Alexandre Pato", "AC Milan")');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Van Persie", "Arsenal")');
}
//function will be called when an error occurred
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
//function will be called when process succeed
function successCB() {
alert("success!");
db.transaction(queryDB,errorCB);
}
110. create table and insert some record
When successCB() run, it does another transaction to the database which will retrieve all record from SoccerPlayer table.
And the query result stored in array which then will be displayed in html with listview style.
111. create table and insert some record
function queryDB(tx){
tx.executeSql('SELECT * FROM SoccerPlayer',[],querySuccess,errorCB);
}
function querySuccess(tx,result){
$('#SoccerPlayerList').empty();
$.each(result.rows,function(index){
var row = result.rows.item(index);
$('#SoccerPlayerList').append('<li><a href="#"><h3 class="ui-li- heading">'+row['Name']+'</h3><p class="ui-li-desc">Club '+row['Club']+'</p></a></li>');
});
$('#SoccerPlayerList').listview();
}
112. you can run it on your android device or emulator