SlideShare a Scribd company logo
1 of 114
Download to read offline
Introduction to PhoneGap 
Rakesh Kumar Jha 
M.Tech, MBA
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
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.
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.
Introduction to PhoneGap 
• PhoneGap produces apps for all popular mobile OS platforms such as iOS, Android, BlackBerry, and Windows Mobile OS etc
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.
Introduction of Phonegap 
•Mobile, handhelds and easy-to-carry devices have started a new revolution in software engineering.
Introduction of Phonegap 
•These small but efficient devices are capable to run applications created with high-end programming languages.
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.
PhoneGap Architecture
PhoneGap Architecture 
•These three items are mostly proprietary and are engineered, developed, and assembled under one flagship organization.
PhoneGap Architecture 
•Apps (Application Software) are developed both by flagship organization and developers from outside the organization.
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
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
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.
PhoneGap
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
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.
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.
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.
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)
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.
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>
config.xml 
<preference name="permissions" value="none"/> 
<icon src="res/icon/android/drawable-ldpi/tp_icon.png" gap:platform="android" gap:qualifier="ldpi" /> 
<icon src="res/icon/android/drawable-mdpi/tp_icon.png" gap:platform="android" gap:qualifier="mdpi" /> 
<icon src="res/icon/android/drawable-hdpi/tp_icon.png" gap:platform="android" gap:qualifier="hdpi" /> 
<icon src="res/icon/android/drawable-xhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xhdpi" /> 
<icon src="res/icon/android/drawable-xxhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xxhdpi" /> 
<icon src="res/icon/ios/Icon-72.png" gap:platform="ios" gap:qualifier=""/> 
<icon src="res/icon/ios/icon-57.png" gap:platform="ios" width="57" height="57" /> 
<icon src="res/icon/ios/icon-72.png" gap:platform="ios" width="72" height="72" /> 
<icon src="res/icon/ios/icon-57-2x.png" gap:platform="ios" width="114" height="114" /> 
<icon src="res/icon/ios/icon-72-2x.png" gap:platform="ios" width="144" height="144" /> 
</widget>
config.xml 
<preference name="permissions" value="none"/> 
<icon src="res/icon/android/drawable-ldpi/tp_icon.png" gap:platform="android" gap:qualifier="ldpi" /> 
<icon src="res/icon/android/drawable-mdpi/tp_icon.png" gap:platform="android" gap:qualifier="mdpi" /> 
<icon src="res/icon/android/drawable-hdpi/tp_icon.png" gap:platform="android" gap:qualifier="hdpi" /> 
<icon src="res/icon/android/drawable-xhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xhdpi" /> 
<icon src="res/icon/android/drawable-xxhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xxhdpi" /> 
<icon src="res/icon/ios/Icon-72.png" gap:platform="ios" gap:qualifier=""/> 
<icon src="res/icon/ios/icon-57.png" gap:platform="ios" width="57" height="57" /> 
<icon src="res/icon/ios/icon-72.png" gap:platform="ios" width="72" height="72" /> 
<icon src="res/icon/ios/icon-57-2x.png" gap:platform="ios" width="114" height="114" /> 
<icon src="res/icon/ios/icon-72-2x.png" gap:platform="ios" width="144" height="144" /> 
</widget>
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">
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.
config.xml 
•This is a brief description of what is the app about, and what it is. 
<description> My First Web App </description>
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>
Event Types 
•deviceready 
•pause 
•resume 
•backbutton 
•menubutton 
•searchbutton 
•startcallbutton 
•endcallbutton 
•volumedownbutton 
•volumeupbutton
Event Types 
•Events added by org.apache.cordova.battery- status 
–batterycritical 
–batterylow 
–batterystatus
Event Types 
•Events added by org.apache.cordova.network-information 
–online 
–offline
deviceready 
document.addEventListener("deviceready", yourCallbackFunction, false); 
document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // Now safe to use device APIs }
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>
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
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>
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.
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>
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
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>
menubutton 
document.addEventListener("menubutton", yourCallbackFunction, false); 
•Applying an event handler overrides the default menu button behavior. 
•Applications typically should use document.addEventListener to attach an event listener once the deviceready event fires
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>
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.
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>
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);
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>
Getting Information from the Device
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)
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);
Getting Information from the Device 
<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<meta name="format-detection" content="telephone=no" /> 
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> 
<link rel="stylesheet" type="text/css" href="jquery.mobile-1.2.0.css" /> 
<script type="text/javascript" src="jquery-1.8.2.js"></script> 
<script type="text/javascript" src="jquery.mobile-1.2.0.js"></script> 
<script type="text/javascript"> 
$(document).on("pageinit", "#newpage", function () { 
$('#saveButton').click(function () { 
localStorage.setItem("name", $('#name').val()); 
}); 
}); 
var wID = navigator.accelerometer.watchAcceleration(onSucess, onerror, { frequency: 1000 }); 
function onSucess(a) { 
$('#aX').html(a.x); 
$('#aY').html(a.y); 
$('#aZ').html(a.z); 
$('#aTime').html(a.timestamp); 
} 
function onError() { 
}
Getting Information from the Device 
var phoneName = window.device.name; 
var phoneName = device.name; 
$('#devicename').html(device.name); 
$('#devicephonegap').html(device.phonegap); 
$('#devicplatform').html(device.platform); 
$('#deviceuuid').html(device.uuid); 
$('#deviceversion').html(device.version); 
$(document).on('pageshow', '#newpage', function () { 
var personName = localStorage.getItem("name"); 
if (personName.length > 0) { 
$('#name').val(personName); 
} 
}); 
</script> 
<title>Hello World 2</title> 
</head> 
<body> 
<div id="home" data-role="page"> 
<div data-role="header"> 
<h1>Home Page2</h1> 
</div> 
<div data-role="content"> 
hello Phone Gap and JQuery Mobile! 
<a href="#newpage" data-role="button">new page</a> 
<br> 
<p id="devicename"> </p> 
<p id="devicephonegap"> </p> 
<p id="deviceplatform"> </p> 
<p id="deviceuuid"> </p> 
<p id="deviceversion"> </p> 
<p id="ax"> </p> 
<p id="ay"> </p> 
<p id="az"> </p> 
<p id="aTime"> </p> 
</div>
Getting Information from the Device 
<div id="newpage" data-role="page"> 
<div data-role="header"> 
<a href="#home" data-icon="delete">Cancel</a> 
<h1>New Page</h1> 
<a href=#home" data-icon="save">save</a> 
</div> 
<div data-role="content"> 
<label for="name">what is your name?</label> 
<input id="name" type="text" name="name" value="" /> 
<a id="saveButton" href="" data-role="button">Save</a> 
</div> 
<div data-role="footer" data-position="fixed"> 
<h4> 
footer</h4> 
</div> 
</div> 
<div id="dialogpage" data-role="page"> 
<div data-role="header"> 
<h1>Dialog</h1> 
</div> 
<div data-role="content"> 
this is a dialog 
</div> 
</div> 
<script type="text/javascript" src="cordova-2.1.0.js"></script> 
<script type="text/javascript" src="js/index.js"></script> 
<script type="text/javascript"> 
app.initialize(); 
</script> 
</body> 
</html>
Device Info 
<!DOCTYPE html> <html> <head> <title>Device Properties 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() { var element = document.getElementById('deviceProperties'); element.innerHTML = 'Device Name: ' + device.name + '<br />' + 'Device Cordova: ' + device.cordova + '<br />' + 'Device Platform: ' + device.platform + '<br />' + 'Device UUID: ' + device.uuid + '<br />' + 'Device Version: ' + device.version + '<br />'; } </script> </head> <body> <p id="deviceProperties">Loading device properties...</p> </body> </html>
Using Notifications
Notification 
•Visual, audible, and tactile device notifications
Notification 
•Methods 
–notification.alert 
–notification.confirm 
–notification.beep 
–notification.vibrate
Notification Permissions 
•app/res/xml/plugins.xml 
<plugin name="Notification" value="org.apache.cordova.Notification"/> 
•app/AndroidManifest.xml 
<uses-permission android:name="android.permission.VIBRATE" />
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")
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.
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 );
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>
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")
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>
notification.beep 
•The device will play a beep sound. 
navigator.notification.beep(times);
notification.beep 
<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 } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message 'Game Over', // title 'Done' // buttonName ); } // Beep three times // function playBeep() { navigator.notification.beep(3); } // Vibrate for 2 seconds // function vibrate() { navigator.notification.vibrate(2000); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> <p><a href="#" onclick="playBeep(); return false;">Play Beep</a></p> <p><a href="#" onclick="vibrate(); return false;">Vibrate</a></p> </body> </html>
notification.beep 
<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 } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message 'Game Over', // title 'Done' // buttonName ); } // Beep three times // function playBeep() { navigator.notification.beep(3); } // Vibrate for 2 seconds // function vibrate() { navigator.notification.vibrate(2000); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> <p><a href="#" onclick="playBeep(); return false;">Play Beep</a></p> <p><a href="#" onclick="vibrate(); return false;">Vibrate</a></p> </body> </html>
notification.vibrate 
•Vibrates the device for the specified amount of time. 
navigator.notification.vibrate(milliseconds)
notification.vibrate 
<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 } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message 'Game Over', // title 'Done' // buttonName ); } // Beep three times // function playBeep() { navigator.notification.beep(3); } // Vibrate for 2 seconds // function vibrate() { navigator.notification.vibrate(2000); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> <p><a href="#" onclick="playBeep(); return false;">Play Beep</a></p> <p><a href="#" onclick="vibrate(); return false;">Vibrate</a></p> </body> </html>
Accelerometer
Accelerometer 
•Captures device motion in the x, y, and z direction.
Accelerometer 
•Methods 
–accelerometer.getCurrentAcceleration 
–accelerometer.watchAcceleration 
–accelerometer.clearWatch
Accelerometer 
•Arguments 
–accelerometerSuccess 
–accelerometerError 
–accelerometerOptions
Accelerometer Permissions 
•app/res/xml/plugins.xml 
<plugin name="Accelerometer" value="org.apache.cordova.AccelListener" />
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
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>
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)
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>
Media
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); 
}
Installation 
cordova plugin add org.apache.cordova.media
Media 
var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]);
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)
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)
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]);
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)
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;
Media Permissions 
•app/res/xml/plugins.xml 
<plugin name="Media" value="org.apache.cordova.AudioHandler" /> 
• app/AndroidManifest.xml 
<uses-permission android:name="android.permission.RECORD_AUDIO" /> 
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!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>
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.
<!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>
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);
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);
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
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(); 
}
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(); 
}
Day 10
Contents 
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
Storage
Storage 
•Several storage APIs are available for Cordova applications 
•LocalStorage 
•WebSQL 
•IndexedDB
•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.
Index file 
<!DOCTYPE html> 
<html> 
<head> 
<title>Page Title</title> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="stylesheet" href="jquery.mobile-1.0rc2.min.css" /> 
<script type="text/javascript" src="js/phonegap-1.1.0.js"></script> 
<script type="text/javascript" src="js/jquery.min.js"/></script> 
<script type="text/javascript" src="js/jquery.mobile-1.0rc2.min.js"></script> 
</head> 
<body> 
<div data-role="page"> 
<div data-role="header" data-position="fixed" data-theme="b"> 
<h1>Soccer Player</h1> 
</div> 
<div data-role="content"> 
<ul id="SoccerPlayerList"> 
</ul> 
</div> 
</div> 
<!--end of Soccer Player Page---> 
</body> 
</html>
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(); 
}
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 ?
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.
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); 
}
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.
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); 
}
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.
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(); 
}
you can run it on your android device or emulator
Contacts
Advanced programing in phonegap

More Related Content

What's hot

Cross-Platform Development using Angulr JS in Visual Studio
Cross-Platform Development using Angulr JS in Visual StudioCross-Platform Development using Angulr JS in Visual Studio
Cross-Platform Development using Angulr JS in Visual StudioMizanur Sarker
 
Building Native Mobile Applications with PhoneGap
Building Native Mobile Applications with PhoneGapBuilding Native Mobile Applications with PhoneGap
Building Native Mobile Applications with PhoneGapSimon MacDonald
 
Developing Mobile Applications for iOS and Android the Oracle way
Developing Mobile Applications for iOS and Android the Oracle wayDeveloping Mobile Applications for iOS and Android the Oracle way
Developing Mobile Applications for iOS and Android the Oracle wayToronto-Oracle-Users-Group
 
Introduction to PhoneGap
Introduction to PhoneGapIntroduction to PhoneGap
Introduction to PhoneGapRamesh Nair
 
Apps multiplataforma com HTML5
Apps multiplataforma com HTML5Apps multiplataforma com HTML5
Apps multiplataforma com HTML5Jomar Silva
 
Flash Builder and Flex Future - Multiscreen Development
Flash Builder and Flex Future - Multiscreen DevelopmentFlash Builder and Flex Future - Multiscreen Development
Flash Builder and Flex Future - Multiscreen DevelopmentRyan Stewart
 
Building Mobile Apps with Cordova , AngularJS and Ionic
Building Mobile Apps with Cordova , AngularJS and IonicBuilding Mobile Apps with Cordova , AngularJS and Ionic
Building Mobile Apps with Cordova , AngularJS and IonicKadhem Soltani
 
TechTalk: Taking the Mystery Out of Object ID Automation
TechTalk: Taking the Mystery Out of Object ID AutomationTechTalk: Taking the Mystery Out of Object ID Automation
TechTalk: Taking the Mystery Out of Object ID AutomationLizzy Guido (she/her)
 
Android voice skill sprint
Android voice skill sprintAndroid voice skill sprint
Android voice skill sprintJim McKeeth
 
Progressive Web Apps and React
Progressive Web Apps and ReactProgressive Web Apps and React
Progressive Web Apps and ReactMike Melusky
 
Development mobile app cross device
Development mobile app cross deviceDevelopment mobile app cross device
Development mobile app cross devicePhuong Nguyen
 
Intro to PhoneGap and PhoneGap Build
Intro to PhoneGap and PhoneGap BuildIntro to PhoneGap and PhoneGap Build
Intro to PhoneGap and PhoneGap BuildChris Griffith
 
Desenvolvimento Apps multiplataforma para dispositivos móveis usando HTML5
Desenvolvimento Apps multiplataforma para dispositivos móveis usando HTML5Desenvolvimento Apps multiplataforma para dispositivos móveis usando HTML5
Desenvolvimento Apps multiplataforma para dispositivos móveis usando HTML5Intel Software Brasil
 

What's hot (20)

Webapi
WebapiWebapi
Webapi
 
Cross-Platform Development using Angulr JS in Visual Studio
Cross-Platform Development using Angulr JS in Visual StudioCross-Platform Development using Angulr JS in Visual Studio
Cross-Platform Development using Angulr JS in Visual Studio
 
Building Native Mobile Applications with PhoneGap
Building Native Mobile Applications with PhoneGapBuilding Native Mobile Applications with PhoneGap
Building Native Mobile Applications with PhoneGap
 
Resume(1)
Resume(1)Resume(1)
Resume(1)
 
Developing Mobile Applications for iOS and Android the Oracle way
Developing Mobile Applications for iOS and Android the Oracle wayDeveloping Mobile Applications for iOS and Android the Oracle way
Developing Mobile Applications for iOS and Android the Oracle way
 
Phone gap development, testing, and debugging
Phone gap development, testing, and debuggingPhone gap development, testing, and debugging
Phone gap development, testing, and debugging
 
Architecting iOS Project
Architecting iOS ProjectArchitecting iOS Project
Architecting iOS Project
 
Introduction to PhoneGap
Introduction to PhoneGapIntroduction to PhoneGap
Introduction to PhoneGap
 
Android - Anroid Pproject
Android - Anroid PprojectAndroid - Anroid Pproject
Android - Anroid Pproject
 
Apps multiplataforma com HTML5
Apps multiplataforma com HTML5Apps multiplataforma com HTML5
Apps multiplataforma com HTML5
 
Flash Builder and Flex Future - Multiscreen Development
Flash Builder and Flex Future - Multiscreen DevelopmentFlash Builder and Flex Future - Multiscreen Development
Flash Builder and Flex Future - Multiscreen Development
 
Building Mobile Apps with Cordova , AngularJS and Ionic
Building Mobile Apps with Cordova , AngularJS and IonicBuilding Mobile Apps with Cordova , AngularJS and Ionic
Building Mobile Apps with Cordova , AngularJS and Ionic
 
TechTalk: Taking the Mystery Out of Object ID Automation
TechTalk: Taking the Mystery Out of Object ID AutomationTechTalk: Taking the Mystery Out of Object ID Automation
TechTalk: Taking the Mystery Out of Object ID Automation
 
Android voice skill sprint
Android voice skill sprintAndroid voice skill sprint
Android voice skill sprint
 
Hybrid HTML5 Apps
Hybrid HTML5 AppsHybrid HTML5 Apps
Hybrid HTML5 Apps
 
Progressive Web Apps and React
Progressive Web Apps and ReactProgressive Web Apps and React
Progressive Web Apps and React
 
Development mobile app cross device
Development mobile app cross deviceDevelopment mobile app cross device
Development mobile app cross device
 
Intro to PhoneGap and PhoneGap Build
Intro to PhoneGap and PhoneGap BuildIntro to PhoneGap and PhoneGap Build
Intro to PhoneGap and PhoneGap Build
 
Desenvolvimento Apps multiplataforma para dispositivos móveis usando HTML5
Desenvolvimento Apps multiplataforma para dispositivos móveis usando HTML5Desenvolvimento Apps multiplataforma para dispositivos móveis usando HTML5
Desenvolvimento Apps multiplataforma para dispositivos móveis usando HTML5
 
Codename one
Codename oneCodename one
Codename one
 

Similar to Advanced programing in phonegap

phonegap with angular js for freshers
phonegap with angular js for freshers    phonegap with angular js for freshers
phonegap with angular js for freshers dssprakash
 
"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGap"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGapChristian Rokitta
 
Phonegap android
Phonegap androidPhonegap android
Phonegap androidumesh patil
 
Dreamweaver CS6, jQuery, PhoneGap, mobile design
Dreamweaver CS6, jQuery, PhoneGap, mobile designDreamweaver CS6, jQuery, PhoneGap, mobile design
Dreamweaver CS6, jQuery, PhoneGap, mobile designDee Sadler
 
Hybrid application development
Hybrid application developmentHybrid application development
Hybrid application developmentEngin Hatay
 
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)Ryan Cuprak
 
Mobile Apps with PhoneGap and jQuery Mobile
Mobile Apps with PhoneGap and jQuery MobileMobile Apps with PhoneGap and jQuery Mobile
Mobile Apps with PhoneGap and jQuery MobileTerry Ryan
 
Getting Acquainted with PhoneGap
Getting Acquainted with PhoneGapGetting Acquainted with PhoneGap
Getting Acquainted with PhoneGapJoseph Labrecque
 
移动端Web app开发
移动端Web app开发移动端Web app开发
移动端Web app开发Zhang Xiaoxue
 
Fixing the mobile web - Internet World Romania
Fixing the mobile web - Internet World RomaniaFixing the mobile web - Internet World Romania
Fixing the mobile web - Internet World RomaniaChristian Heilmann
 
Android Workshop
Android WorkshopAndroid Workshop
Android WorkshopJunda Ong
 
Apache Cordova phonegap plugins for mobile app development
Apache Cordova phonegap plugins for mobile app developmentApache Cordova phonegap plugins for mobile app development
Apache Cordova phonegap plugins for mobile app developmentwebprogr.com
 

Similar to Advanced programing in phonegap (20)

Intro to PhoneGap
Intro to PhoneGapIntro to PhoneGap
Intro to PhoneGap
 
phonegap with angular js for freshers
phonegap with angular js for freshers    phonegap with angular js for freshers
phonegap with angular js for freshers
 
"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGap"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGap
 
Phonegap android
Phonegap androidPhonegap android
Phonegap android
 
Phone gap development, testing, and debugging
Phone gap development, testing, and debuggingPhone gap development, testing, and debugging
Phone gap development, testing, and debugging
 
Dreamweaver CS6, jQuery, PhoneGap, mobile design
Dreamweaver CS6, jQuery, PhoneGap, mobile designDreamweaver CS6, jQuery, PhoneGap, mobile design
Dreamweaver CS6, jQuery, PhoneGap, mobile design
 
Apache cordova
Apache cordovaApache cordova
Apache cordova
 
Hybrid application development
Hybrid application developmentHybrid application development
Hybrid application development
 
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
 
phonegap_101
phonegap_101phonegap_101
phonegap_101
 
Mobile Apps with PhoneGap and jQuery Mobile
Mobile Apps with PhoneGap and jQuery MobileMobile Apps with PhoneGap and jQuery Mobile
Mobile Apps with PhoneGap and jQuery Mobile
 
Getting Acquainted with PhoneGap
Getting Acquainted with PhoneGapGetting Acquainted with PhoneGap
Getting Acquainted with PhoneGap
 
Introducing J2ME Polish
Introducing J2ME PolishIntroducing J2ME Polish
Introducing J2ME Polish
 
移动端Web app开发
移动端Web app开发移动端Web app开发
移动端Web app开发
 
Fixing the mobile web - Internet World Romania
Fixing the mobile web - Internet World RomaniaFixing the mobile web - Internet World Romania
Fixing the mobile web - Internet World Romania
 
PhoneGap/Cordova
PhoneGap/CordovaPhoneGap/Cordova
PhoneGap/Cordova
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 
Apache Cordova
Apache CordovaApache Cordova
Apache Cordova
 
Intro to appcelerator
Intro to appceleratorIntro to appcelerator
Intro to appcelerator
 
Apache Cordova phonegap plugins for mobile app development
Apache Cordova phonegap plugins for mobile app developmentApache Cordova phonegap plugins for mobile app development
Apache Cordova phonegap plugins for mobile app development
 

More from Rakesh Jha

Whitep paper on Emerging java and .net technology and critical trends
Whitep paper on Emerging java and .net technology and critical trendsWhitep paper on Emerging java and .net technology and critical trends
Whitep paper on Emerging java and .net technology and critical trendsRakesh Jha
 
Ways to be a great project manager
Ways to be a great project managerWays to be a great project manager
Ways to be a great project managerRakesh Jha
 
What is mobile wallet
What is mobile walletWhat is mobile wallet
What is mobile walletRakesh Jha
 
Cordova vs xamarin vs titanium
Cordova vs xamarin vs titaniumCordova vs xamarin vs titanium
Cordova vs xamarin vs titaniumRakesh Jha
 
Mobile applications testing (challenges, tools & techniques)
Mobile applications testing (challenges, tools & techniques)Mobile applications testing (challenges, tools & techniques)
Mobile applications testing (challenges, tools & techniques)Rakesh Jha
 
Mobile testing practices
Mobile testing practicesMobile testing practices
Mobile testing practicesRakesh Jha
 
Introduction phonegap
Introduction phonegapIntroduction phonegap
Introduction phonegapRakesh Jha
 
Advanced JQuery Mobile tutorial with Phonegap
Advanced JQuery Mobile tutorial with Phonegap Advanced JQuery Mobile tutorial with Phonegap
Advanced JQuery Mobile tutorial with Phonegap Rakesh Jha
 
Basics of css3
Basics of css3 Basics of css3
Basics of css3 Rakesh Jha
 
Introduction to jquery mobile with Phonegap
Introduction to jquery mobile with PhonegapIntroduction to jquery mobile with Phonegap
Introduction to jquery mobile with PhonegapRakesh Jha
 
Basics of HTML5 for Phonegap
Basics of HTML5 for PhonegapBasics of HTML5 for Phonegap
Basics of HTML5 for PhonegapRakesh Jha
 
Introduction of phonegap installation and configuration of Phonegap with An...
Introduction of phonegap   installation and configuration of Phonegap with An...Introduction of phonegap   installation and configuration of Phonegap with An...
Introduction of phonegap installation and configuration of Phonegap with An...Rakesh Jha
 
Android ndk - Introduction
Android ndk  - IntroductionAndroid ndk  - Introduction
Android ndk - IntroductionRakesh Jha
 
Native development kit (ndk) introduction
Native development kit (ndk)  introductionNative development kit (ndk)  introduction
Native development kit (ndk) introductionRakesh Jha
 
User experience and interactions design
User experience and interactions design User experience and interactions design
User experience and interactions design Rakesh Jha
 
Android coding standard
Android coding standard Android coding standard
Android coding standard Rakesh Jha
 
Optimisation and performance in Android
Optimisation and performance in AndroidOptimisation and performance in Android
Optimisation and performance in AndroidRakesh Jha
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
Advance ui development and design
Advance ui  development and design Advance ui  development and design
Advance ui development and design Rakesh Jha
 
Android Design Architecture
Android Design ArchitectureAndroid Design Architecture
Android Design ArchitectureRakesh Jha
 

More from Rakesh Jha (20)

Whitep paper on Emerging java and .net technology and critical trends
Whitep paper on Emerging java and .net technology and critical trendsWhitep paper on Emerging java and .net technology and critical trends
Whitep paper on Emerging java and .net technology and critical trends
 
Ways to be a great project manager
Ways to be a great project managerWays to be a great project manager
Ways to be a great project manager
 
What is mobile wallet
What is mobile walletWhat is mobile wallet
What is mobile wallet
 
Cordova vs xamarin vs titanium
Cordova vs xamarin vs titaniumCordova vs xamarin vs titanium
Cordova vs xamarin vs titanium
 
Mobile applications testing (challenges, tools & techniques)
Mobile applications testing (challenges, tools & techniques)Mobile applications testing (challenges, tools & techniques)
Mobile applications testing (challenges, tools & techniques)
 
Mobile testing practices
Mobile testing practicesMobile testing practices
Mobile testing practices
 
Introduction phonegap
Introduction phonegapIntroduction phonegap
Introduction phonegap
 
Advanced JQuery Mobile tutorial with Phonegap
Advanced JQuery Mobile tutorial with Phonegap Advanced JQuery Mobile tutorial with Phonegap
Advanced JQuery Mobile tutorial with Phonegap
 
Basics of css3
Basics of css3 Basics of css3
Basics of css3
 
Introduction to jquery mobile with Phonegap
Introduction to jquery mobile with PhonegapIntroduction to jquery mobile with Phonegap
Introduction to jquery mobile with Phonegap
 
Basics of HTML5 for Phonegap
Basics of HTML5 for PhonegapBasics of HTML5 for Phonegap
Basics of HTML5 for Phonegap
 
Introduction of phonegap installation and configuration of Phonegap with An...
Introduction of phonegap   installation and configuration of Phonegap with An...Introduction of phonegap   installation and configuration of Phonegap with An...
Introduction of phonegap installation and configuration of Phonegap with An...
 
Android ndk - Introduction
Android ndk  - IntroductionAndroid ndk  - Introduction
Android ndk - Introduction
 
Native development kit (ndk) introduction
Native development kit (ndk)  introductionNative development kit (ndk)  introduction
Native development kit (ndk) introduction
 
User experience and interactions design
User experience and interactions design User experience and interactions design
User experience and interactions design
 
Android coding standard
Android coding standard Android coding standard
Android coding standard
 
Optimisation and performance in Android
Optimisation and performance in AndroidOptimisation and performance in Android
Optimisation and performance in Android
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Advance ui development and design
Advance ui  development and design Advance ui  development and design
Advance ui development and design
 
Android Design Architecture
Android Design ArchitectureAndroid Design Architecture
Android Design Architecture
 

Recently uploaded

CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceanilsa9823
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPsychicRuben LoveSpells
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceanilsa9823
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Pooja Nehwal
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceDelhi Call girls
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7Pooja Nehwal
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRnishacall1
 

Recently uploaded (7)

CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
 

Advanced programing in phonegap

  • 1. Introduction to PhoneGap Rakesh Kumar Jha M.Tech, MBA
  • 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>
  • 25. config.xml <preference name="permissions" value="none"/> <icon src="res/icon/android/drawable-ldpi/tp_icon.png" gap:platform="android" gap:qualifier="ldpi" /> <icon src="res/icon/android/drawable-mdpi/tp_icon.png" gap:platform="android" gap:qualifier="mdpi" /> <icon src="res/icon/android/drawable-hdpi/tp_icon.png" gap:platform="android" gap:qualifier="hdpi" /> <icon src="res/icon/android/drawable-xhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xhdpi" /> <icon src="res/icon/android/drawable-xxhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xxhdpi" /> <icon src="res/icon/ios/Icon-72.png" gap:platform="ios" gap:qualifier=""/> <icon src="res/icon/ios/icon-57.png" gap:platform="ios" width="57" height="57" /> <icon src="res/icon/ios/icon-72.png" gap:platform="ios" width="72" height="72" /> <icon src="res/icon/ios/icon-57-2x.png" gap:platform="ios" width="114" height="114" /> <icon src="res/icon/ios/icon-72-2x.png" gap:platform="ios" width="144" height="144" /> </widget>
  • 26. config.xml <preference name="permissions" value="none"/> <icon src="res/icon/android/drawable-ldpi/tp_icon.png" gap:platform="android" gap:qualifier="ldpi" /> <icon src="res/icon/android/drawable-mdpi/tp_icon.png" gap:platform="android" gap:qualifier="mdpi" /> <icon src="res/icon/android/drawable-hdpi/tp_icon.png" gap:platform="android" gap:qualifier="hdpi" /> <icon src="res/icon/android/drawable-xhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xhdpi" /> <icon src="res/icon/android/drawable-xxhdpi/tp_icon.png" gap:platform="android" gap:qualifier="xxhdpi" /> <icon src="res/icon/ios/Icon-72.png" gap:platform="ios" gap:qualifier=""/> <icon src="res/icon/ios/icon-57.png" gap:platform="ios" width="57" height="57" /> <icon src="res/icon/ios/icon-72.png" gap:platform="ios" width="72" height="72" /> <icon src="res/icon/ios/icon-57-2x.png" gap:platform="ios" width="114" height="114" /> <icon src="res/icon/ios/icon-72-2x.png" gap:platform="ios" width="144" height="144" /> </widget>
  • 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>
  • 31. Event Types •deviceready •pause •resume •backbutton •menubutton •searchbutton •startcallbutton •endcallbutton •volumedownbutton •volumeupbutton
  • 32. Event Types •Events added by org.apache.cordova.battery- status –batterycritical –batterylow –batterystatus
  • 33. Event Types •Events added by org.apache.cordova.network-information –online –offline
  • 34. deviceready document.addEventListener("deviceready", yourCallbackFunction, false); document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // Now safe to use device APIs }
  • 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>
  • 42. menubutton document.addEventListener("menubutton", yourCallbackFunction, false); •Applying an event handler overrides the default menu button behavior. •Applications typically should use document.addEventListener to attach an event listener once the deviceready event fires
  • 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);
  • 51. Getting Information from the Device <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="format-detection" content="telephone=no" /> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> <link rel="stylesheet" type="text/css" href="jquery.mobile-1.2.0.css" /> <script type="text/javascript" src="jquery-1.8.2.js"></script> <script type="text/javascript" src="jquery.mobile-1.2.0.js"></script> <script type="text/javascript"> $(document).on("pageinit", "#newpage", function () { $('#saveButton').click(function () { localStorage.setItem("name", $('#name').val()); }); }); var wID = navigator.accelerometer.watchAcceleration(onSucess, onerror, { frequency: 1000 }); function onSucess(a) { $('#aX').html(a.x); $('#aY').html(a.y); $('#aZ').html(a.z); $('#aTime').html(a.timestamp); } function onError() { }
  • 52. Getting Information from the Device var phoneName = window.device.name; var phoneName = device.name; $('#devicename').html(device.name); $('#devicephonegap').html(device.phonegap); $('#devicplatform').html(device.platform); $('#deviceuuid').html(device.uuid); $('#deviceversion').html(device.version); $(document).on('pageshow', '#newpage', function () { var personName = localStorage.getItem("name"); if (personName.length > 0) { $('#name').val(personName); } }); </script> <title>Hello World 2</title> </head> <body> <div id="home" data-role="page"> <div data-role="header"> <h1>Home Page2</h1> </div> <div data-role="content"> hello Phone Gap and JQuery Mobile! <a href="#newpage" data-role="button">new page</a> <br> <p id="devicename"> </p> <p id="devicephonegap"> </p> <p id="deviceplatform"> </p> <p id="deviceuuid"> </p> <p id="deviceversion"> </p> <p id="ax"> </p> <p id="ay"> </p> <p id="az"> </p> <p id="aTime"> </p> </div>
  • 53. Getting Information from the Device <div id="newpage" data-role="page"> <div data-role="header"> <a href="#home" data-icon="delete">Cancel</a> <h1>New Page</h1> <a href=#home" data-icon="save">save</a> </div> <div data-role="content"> <label for="name">what is your name?</label> <input id="name" type="text" name="name" value="" /> <a id="saveButton" href="" data-role="button">Save</a> </div> <div data-role="footer" data-position="fixed"> <h4> footer</h4> </div> </div> <div id="dialogpage" data-role="page"> <div data-role="header"> <h1>Dialog</h1> </div> <div data-role="content"> this is a dialog </div> </div> <script type="text/javascript" src="cordova-2.1.0.js"></script> <script type="text/javascript" src="js/index.js"></script> <script type="text/javascript"> app.initialize(); </script> </body> </html>
  • 54. Device Info <!DOCTYPE html> <html> <head> <title>Device Properties 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() { var element = document.getElementById('deviceProperties'); element.innerHTML = 'Device Name: ' + device.name + '<br />' + 'Device Cordova: ' + device.cordova + '<br />' + 'Device Platform: ' + device.platform + '<br />' + 'Device UUID: ' + device.uuid + '<br />' + 'Device Version: ' + device.version + '<br />'; } </script> </head> <body> <p id="deviceProperties">Loading device properties...</p> </body> </html>
  • 56. Notification •Visual, audible, and tactile device notifications
  • 57. Notification •Methods –notification.alert –notification.confirm –notification.beep –notification.vibrate
  • 58. Notification Permissions •app/res/xml/plugins.xml <plugin name="Notification" value="org.apache.cordova.Notification"/> •app/AndroidManifest.xml <uses-permission android:name="android.permission.VIBRATE" />
  • 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>
  • 65. notification.beep •The device will play a beep sound. navigator.notification.beep(times);
  • 66. notification.beep <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 } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message 'Game Over', // title 'Done' // buttonName ); } // Beep three times // function playBeep() { navigator.notification.beep(3); } // Vibrate for 2 seconds // function vibrate() { navigator.notification.vibrate(2000); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> <p><a href="#" onclick="playBeep(); return false;">Play Beep</a></p> <p><a href="#" onclick="vibrate(); return false;">Vibrate</a></p> </body> </html>
  • 67. notification.beep <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 } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message 'Game Over', // title 'Done' // buttonName ); } // Beep three times // function playBeep() { navigator.notification.beep(3); } // Vibrate for 2 seconds // function vibrate() { navigator.notification.vibrate(2000); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> <p><a href="#" onclick="playBeep(); return false;">Play Beep</a></p> <p><a href="#" onclick="vibrate(); return false;">Vibrate</a></p> </body> </html>
  • 68. notification.vibrate •Vibrates the device for the specified amount of time. navigator.notification.vibrate(milliseconds)
  • 69. notification.vibrate <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 } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message 'Game Over', // title 'Done' // buttonName ); } // Beep three times // function playBeep() { navigator.notification.beep(3); } // Vibrate for 2 seconds // function vibrate() { navigator.notification.vibrate(2000); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> <p><a href="#" onclick="playBeep(); return false;">Play Beep</a></p> <p><a href="#" onclick="vibrate(); return false;">Vibrate</a></p> </body> </html>
  • 71. Accelerometer •Captures device motion in the x, y, and z direction.
  • 72. Accelerometer •Methods –accelerometer.getCurrentAcceleration –accelerometer.watchAcceleration –accelerometer.clearWatch
  • 73. Accelerometer •Arguments –accelerometerSuccess –accelerometerError –accelerometerOptions
  • 74. Accelerometer Permissions •app/res/xml/plugins.xml <plugin name="Accelerometer" value="org.apache.cordova.AccelListener" />
  • 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>
  • 79. Media
  • 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); }
  • 81. Installation cordova plugin add org.apache.cordova.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;
  • 88. Media Permissions •app/res/xml/plugins.xml <plugin name="Media" value="org.apache.cordova.AudioHandler" /> • app/AndroidManifest.xml <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • 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(); }
  • 98. Contents 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
  • 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.
  • 103. Index file <!DOCTYPE html> <html> <head> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="jquery.mobile-1.0rc2.min.css" /> <script type="text/javascript" src="js/phonegap-1.1.0.js"></script> <script type="text/javascript" src="js/jquery.min.js"/></script> <script type="text/javascript" src="js/jquery.mobile-1.0rc2.min.js"></script> </head> <body> <div data-role="page"> <div data-role="header" data-position="fixed" data-theme="b"> <h1>Soccer Player</h1> </div> <div data-role="content"> <ul id="SoccerPlayerList"> </ul> </div> </div> <!--end of Soccer Player Page---> </body> </html>
  • 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