Sie sind auf Seite 1von 55

The Recipes

Determining Whether the Device Is Ready


Problem
<RXZDQWWRH[HFXWHD3KRQH*DS$3,FDOOEXW\RXDUHXQVXUHZKHWKHUWKHGHYLFHLV
UHDG\DQGWKHDSSOLFDWLRQZLOOQRWIXQFWLRQLIWKH$3,DWWHPSWVWRDFFHVVWKHGHYLFH
SUHPDWXUHO\

Solution
7KHFRUHIXQFWLRQDOLWLHVWKDW3KRQH*DSPDNHVDFFHVVLEOHWKURXJKWKH-DYD6FULSW$3,
GHSHQGRQWKHGHYLFHEHLQJUHDG\KRZHYHU-DYD6FULSWFDQEHJLQZRUNLQJDVVRRQDV
WKH'RFXPHQW2EMHFW0RGHO '20 LVDYDLODEOH7KHUHIRUHEHIRUH\RXSHUIRUPDQ\
$3,FDOO\RXPXVWHQVXUHWKDW3KRQH*DSKDVGHWHUPLQHGWKDWWKHGHYLFHLVUHDG\IRUXVH
7KHUHDUHWZRVROXWLRQVIRUFKHFNLQJZKHWKHUWKHGHYLFHLVUHDG\)RUL26$QGURLG
DQG%ODFN%HUU\ YHUVLRQDQGKLJKHU DFXVWRPHYHQWW\SHWKDW\RXFDQDWWDFKWRWKH
'20LVDYDLODEOHDQG3KRQH*DSZLOOWULJJHUWKLVHYHQWZKHQWKHGHYLFHLVUHDG\

)RUROGHUYHUVLRQVRI%ODFN%HUU\3KRQH*DSLVXQDEOHWRILUHWKHFXVWRP
HYHQW VR \RX PXVW SHUIRUP D EDVLF -DYD6FULSW LQWHUYDO FKHFN IRU D
%RROHDQYDULDEOHWRLQGLFDWHZKHWKHU3KRQH*DSLVUHDG\RUQRW

Discussion
7KURXJKRXWWKHUHFLSHVLQWKLVERRN,ZLOODOZD\VDWWHPSWWRVHSDUDWHWKHFRGHDVPXFK
DV SRVVLEOH PHDQLQJ WKDW -DYD6FULSW ZLOO EH SODFHG LQ MV ILOHV &66 LQ FVV ILOHV DQG
+70/LQKWPOILOHV'XULQJWKHSUHUHTXLVLWHVPHQWLRQHGLQWKH3UHIDFH\RXVKRXOG
KDYHFUHDWHGWZRIROGHUVLQVLGHRI\RXUZZZGLUHFWRU\VFULSWVDQGFVV
7KHFRUHRIWKH-DYD6FULSWFRGHZLOOEHSODFHGLQVLGHRIDILOHFDOOHGFRPPRQMV&UHDWH
WKLVILOHQRZLQVLGHRI\RXUscriptsGLUHFWRU\2QFHFUHDWHGSODFHWKHIROORZLQJFRGH
LQWKHILOH

www.it-ebooks.info
// Global variable that will tell us whether PhoneGap is ready
var isPhoneGapReady = false;

function init() {
// Add an event listener for deviceready
document.addEventListener("deviceready",
onDeviceReady, false);

// Older versions of Blackberry < 5.0 don't support


// PhoneGap's custom events, so instead we need to perform
// an interval check every 500 milliseconds to see whether
// PhoneGap is ready. Once done, the interval will be
// cleared and normal processing can begin.
var intervalID = window.setInterval(function() {
if (PhoneGap.available) {
onDeviceReady();
}
}, 500);
}

function onDeviceReady() {
window.clearInterval(intervalID);

// set to true
isPhoneGapReady = true;

alert('The device is now ready');


}

// Set an onload handler to call the init function


window.onload = init;

7KLV-DYD6FULSWFRGHGRHVRQO\RQHLPSRUWDQWWKLQJLWFUHDWHVDQGVHWVDJOREDOYDULDEOH
FDOOHGisPhoneGapReadyWKDWZLOOEHXVHGLQPDQ\IXWXUHUHFLSHVEHIRUHPDNLQJ3KRQH
*DSVSHFLILF$3,FDOOV
7RNQRZZKHWKHUWKHGHYLFHLVUHDG\3KRQH*DSFUHDWHVDQGWULJJHUVDFXVWRPZLQGRZ
HYHQWFDOOHG deviceready%\OLVWHQLQJIRUWKLVHYHQWWKHYDULDEOHFDQEHFKDQJHGDF
FRUGLQJO\7KHDOHUWLVXVHIXOIRUWHVWLQJEXWRIFRXUVH\RXVKRXOGUHPRYHLWIRUSUR
GXFWLRQXVH
,QWKHFRGH,¦YHSODFHGDODUJHEORFNFRPPHQWXQGHUQHDWKWKHHYHQWOLVWHQHUEHFDXVH
ROGHUYHUVLRQVRI%ODFN%HUU\GRQRWVXSSRUWFUHDWLQJFXVWRPHYHQWV,QVWHDGWKHFRGH
PXVWFKHFNWKHPhoneGap.availableYDULDEOHHYHU\PLOOLVHFRQGVWRVHHLILWLVUHDG\
2QFHLWLVWKHLQWHUYDOLVFOHDUHGDQGWKHonDeviceReadyIXQFWLRQLVFDOOHGWKHVDPHDV
ZKDWWKHHYHQWOLVWHQHUFUHDWHGSUHYLRXVO\
)LQDOO\WKHLQGH[KWPOILOHPXVWEHXSGDWHGWRLQFOXGHWKLV-DYD6FULSWILOH
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8"

2 | The Recipes

www.it-ebooks.info
src="scripts/phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8"
src="scripts/common.js"></script>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

,QWKH+70/VDPSOHWKH3KRQH*DS-DYD6FULSWILOHLVEHLQJUHIHUHQFHG
LQVLGHRIWKH scriptsGLUHFWRU\%HVXUHWRFRS\\RXU3KRQH*DS-DYD
6FULSWILOHLQVLGHRIWKLVGLUHFWRU\$OVR\RXPLJKWEHUHTXLUHGWRXSGDWH
WKHYHUVLRQGHSHQGLQJRQWKHODWHVWDYDLODEOHYHUVLRQ

<RXPLJKWQRWLFHWKDW,¦YHVSHFLILHGDQ+70/doctype0DQ\RIWKHQHZHVWSKRQHV
VXSSRUWDORWRIWKHIHDWXUHVRI+70/ZKLFKRSHQXSDZKROHZRUOGRISRVVLELOLWLHV
WRFUHDWHFURVVSODWIRUPLQWHUDFWLYLW\

See Also
-DYD6FULSW(YHQWV

Retrieving Information About the Device


Problem
<RXZDQWWRDGGIXQFWLRQDOLW\WKDWLVDYDLODEOHRQO\RQDFHUWDLQGHYLFHRUSODWIRUP

Solution
&HUWDLQIHDWXUHVRIWKH3KRQH*DS$3,DUHRQO\DYDLODEOHWRFHUWDLQKDQGVHWV7RDYRLG
OLPLWLQJWKHIHDWXUHVRYHUDOOE\GHWHFWLQJWKHGHYLFHW\SH\RXFDQRIIHUGLIIHUHQWIHDWXUHV
IRUL26$QGURLGRUGLIIHUHQW%ODFN%HUU\YHUVLRQV
7KH3KRQH*DS$3,H[SRVHVDJOREDOVWUXFWXUHFDOOHGdeviceWKDWFRQWDLQVLQIRUPDWLRQ
DERXWWKHGHYLFHYHUVLRQ88,'SODWIRUPDQGQDPH(DFKSURSHUW\FDQEHDFFHVVHG
WKURXJK-DYD6FULSW

Discussion
7KHUHDUHTXLWHREYLRXVO\DORWRIGLIIHUHQFHVDPRQJWKHYDULRXVVPDUWSKRQHVWRGD\
%HFDXVHRIWKHVHGLIIHUHQFHVLW¦VLPSRUWDQWWREHDZDUHRIZKDWGHYLFH\RXUDSSOLFDWLRQ
LVUXQQLQJRQ$WDOOWLPHVRXUJRDOLVWRKDYHWRPDLQWDLQRQO\RQHFRGHVHWEXWWKDW
GRHVQ¦WPHDQWKDW\RXFDQQRWDGGDGGLWLRQDOIHDWXUHVWKDWVSHFLILFSKRQHVVXSSRUW

Retrieving Information About the Device | 3

www.it-ebooks.info
%HORZDUHVRPHEDVLF-DYD6FULSWH[DPSOHVRIKRZ\RXFDQDFFHVVHDFKSURSHUW\DYDLO
DEOHLQWKHGHYLFHVWUXFWXUH
var deviceName = device.name;
var deviceVersion = device.version;
var devicePlatform = device.platform;
var deviceUUID = device.uuid;
var phoneGapVersion = device.phonegap;

1RWKLQJWRRVSHFLDOLVKDSSHQLQJKHUHHDFKSURSHUW\LVEHLQJVWRUHGWRDJOREDOYDULDEOH
7KHIROORZLQJH[DPSOHUHWULHYHVWKHGHYLFH¦VSODWIRUPLQIRUPDWLRQDIWHU3KRQH*DSLQ
IRUPVWKHDSSOLFDWLRQWKDWWKHGHYLFHLVUHDG\%DVHGRQWKHLQIRUPDWLRQUHWXUQHGWKH
FRGHVHWVDJOREDOYDULDEOHWKDWFDQEHXVHGLQIXWXUHFRGHH[DPSOHVWRWDUJHWGHYLFH
VSHFLILFLPSOHPHQWDWLRQV
// Global variable that will tell us whether PhoneGap is ready
var isPhoneGapReady = false;

// Default all phone types to false


var isAndroid = false;
var isBlackberry = false;
var isIphone = false;
var isWindows = false;

// Store the device's uuid


var deviceUUID;

function init() {
// Add an event listener for deviceready
document.addEventListener("deviceready",
onDeviceReady, false);
}

function onDeviceReady() {
// set to true
isPhoneGapReady = true;

deviceUUID = device.uuid;

// detect the device's platform


deviceDetection();
}

function deviceDetection() {
if (isPhoneGapReady) {
switch (device.platform) {
case "Android":
isAndroid = true;
break;
case "Blackberry":
isBlackberry = true;
break;
case "iPhone":
isIphone = true;

4 | The Recipes

www.it-ebooks.info
break;
case "WinCE":
isWindows = true;
break;
}

alert("Detected you are using a " + device.platform);


}
}

// Set an onload handler to call the init function


window.onload = init;

0RVWRIWKHFRGHLVWKHVDPHDVWKHILUVWUHFLSHZLWKDIHZQRWDEOHDGGLWLRQV)LUVWO\
VHYHUDOJOREDO%RROHDQYDULDEOHVDUHGHILQHGRQHIRUHDFKRIWKHSRVVLEOHSKRQHW\SHV
7KH\DOOGHIDXOWWRfalseDVQRGHWHFWLRQKDVEHHQSHUIRUPHG\HW

,QWKHDERYHFRGHVDPSOHWKHLQWHUYDOGHYLFHUHDG\FKHFNIRUROGHUYHU
VLRQVRI%ODFN%HUU\KDVEHHQUHPRYHG,I\RXZLVKWRUHOHDVH\RXUDS
SOLFDWLRQWDUJHWLQJWKLVYHUVLRQLWVKRXOGEHOHIWLQ

1H[WLQVLGHRIWKHonDeviceReadyIXQFWLRQWKHJOREDOYDULDEOHWKDWVWRUHVWKH88,'LV
VHW5LJKWEHQHDWKWKLVLVDIXQFWLRQFDOOWRdeviceDetection,QVLGHRIWKLVIXQFWLRQD
VZLWFKVWDWHPHQWLVSHUIRUPHGRQWKH device.platform%DVHGRQWKHFDVHVWDWHPHQW
WKDWLVPDWFKHGWKHDFFRPSDQ\LQJ%RROHDQYDULDEOHLVVHWWRWUXHIRUWKDWSODWIRUP
,Q IXWXUH UHFLSHV LI \RX ZLVK WR WDUJHW L3KRQH RU $QGURLG SODWIRUPV RQO\ \RX FDQ
SHUIRUPDVLPSOHifVWDWHPHQWDVIROORZV
if (isAndroid) {
// Do something for Android only...
}

Creating a Persistent Navigation System


Problem
<RXZDQWWRDOORZWKHXVHUWRQDYLJDWHWRRWKHUSDJHVZKLOHSURYLGLQJDSHUVLVWHQWPHQX
DWWKHERWWRPRIWKHDSSOLFDWLRQ

Solution
7KHL26KDVPDGHLWFRPPRQSODFHWRLQFOXGHDSHUVLVWHQWQDYLJDWLRQEDUWKDWDOORZV
RQHWRXFKDFFHVVWRIUHTXHQWO\XVHGYLHZV7\SLFDOO\WKLVLVORFDWHGDWWKHERWWRPRI
WKHDSSOLFDWLRQ

Creating a Persistent Navigation System | 5

www.it-ebooks.info
7KHEHDXW\RI3KRQH*DSLVWKDWLWDOORZV\RXWRFUHDWHPRELOHDSSOLFDWLRQVWKURXJKWKH
XVHRI+70/-DYD6FULSWDQG&667KHFUHDWRUVRIM4XHU\KDYHFUHDWHGDQH[FHOOHQW
OLEUDU\FDOOHGM4XHU\PRELOHWKDWKHOSVWKHXVHUWRPLPLFWKHQDWLYHORRNDQGIHHORI
PHQXVDQGEXWWRQVRQWKHGHYLFHXVLQJ+70/DQG&66%\XWLOL]LQJWKLVOLEUDU\\RX
FDQHDVLO\DFKLHYHWKHVWDQGDUGIRRWHUPHQXPDWFKLQJWKHFRPPRQIXQFWLRQDOLW\WKDW
VPDUWSKRQHXVHUVKDYHEHFRPHDFFXVWRPHGWR

Discussion
$QDYLJDWLRQV\VWHPLVFUHDWHGWKURXJKVRPHEDVLF+70/OLQNV,I\RXSODFHWKHVHOLQNV
LQVLGHDdivWDJWKDWKDVVRPHDGGLWLRQDOdata-roleDWWULEXWHVDSSOLHGWRLWWKHM4XHU\
PRELOHOLEUDU\ZLOOFRQYHUWWKLVWRDFRQVLVWHQWORRNLQJIRRWHUPHQX,QWKLVH[DPSOH
WZROLQNVDUHFUHDWHGRQHIRUKRPHDQGRQHIRU£DERXW¤:KHQ\RXUXQWKLVH[DPSOH
RQ\RXUSKRQHWKHFRGHZLOODSSHDULQWKHIRRWHURI\RXUGHYLFH%HFDXVHVRPH-DYD
6FULSWZRUNLVSHUIRUPHGWRDOLJQWKHPHQXWRWKHERWWRP\RXPLJKWQRWLFHWKDWWKH
PHQXZLOOVWDUWWRDSSHDUKLJKHUXSWKHQMXPSGRZQ
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<link rel="stylesheet" href="
css/jquery.mobile-1.0rc1.min.css" />
<script type="text/javascript" charset="utf-8"
src="scripts/phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8"
src="scripts/common.js"></script>
<script type="text/javascript" charset="utf-8"
src="scripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript" charset="utf-8"
src="scripts/jquery.mobile-1.0rc1.min.js"></script>
</head>
<body>
<h1>Hello World!</h1>

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html"
class="ui-btn-active">Home</a></li>
<li><a href="about.html">About</a></li>
</ul>
</div>
</div>
</body>
</html>

1HZYHUVLRQVRIWKH-DYD6FULSWOLEUDULHVDUHIUHTXHQWO\UHOHDVHGVREH
VXUHWRUHQDPHWKHILOHQDPHYHUVLRQVLQWKHSUHYLRXVFRGHVDPSOH

6 | The Recipes

www.it-ebooks.info
)LJXUHLVDQH[DPSOHRIZKDWWKHM4XHU\PRELOHOLEUDU\SURGXFHVRQP\$QGURLG
VLPXODWRU

)LJXUH([DPSOHIRRWHUPHQX

7KHNH\+70/WRFUHDWHWKLVPHQXDUHWKHdata-roleDQGdata-position DWWULEXWHVRQ
WKHWZRdivWDJVVXUURXQGLQJWKHOLQNV%\FKDQJLQJWKHVHYDOXHV\RXFDQDOWHUWKHPHQX
WRDSSHDURQWRSRUPDNHLWIORDWE\UHPRYLQJWKHIL[HGSRVLWLRQ
,I\RXZLVKWRVW\OH\RXUPHQXDELWPRUHVHYHUDORWKHUIHDWXUHVFDQEHDGGHG)RU
LQVWDQFH\RXFDQDGGDQLFRQDERYHHDFKOLQNE\DSSO\LQJWKH data-iconDWWULEXWHWR
WKHOLQNWDJ7KHM4XHU\OLEUDU\FRQWDLQVDYDULHW\RISUHGHILQHGLFRQV,I\RXZLVKWR
XVH\RXURZQLFRQVWKLVFDQEHDFFRPSOLVKHGDVIROORZV
<style>
.ui-icon-home-custom {
background-image: url(images/home-icon.png);
}
</style>

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html" data-icon="home-custom"
class="ui-btn-active">Home</a></li>
<li><a href="about.html">About</a></li>
</ul>

Creating a Persistent Navigation System | 7

www.it-ebooks.info
</div>
</div>

7KHhome-icon.pngVKRXOGEHVDYHGDVD31*DQGEHÜSL[HOVLQGLPHQVLRQZLWK
DOSKD WUDQVSDUHQF\ <RX GRQ¦W KDYH WR FRQIRUP WR WKLV FRQYHQWLRQ EXW LW ZLOO KHOS
SURYLGHDPRUHFRQVLVWHQWORRNLQFDVH\RXXVHVRPHRIWKHEXLOWLQLFRQV
$QRWKHUJUHDWZD\WRFXVWRPL]HWKHORRNRI\RXUQDYEDULVWRDOWHUWKHGHIDXOWWKHPH
%\DGGLQJDdata-themeDWWULEXWHWR\RXUPHQXOLQNV\RXFDQDGMXVWWKHFRORUDQGVW\OHV
XVHG&XUUHQWO\M4XHU\FRPHVZLWKILYHEXLOWLQWKHPHV6LPSO\VHWWKHDWWULEXWHYDOXH
abcdRUeWRDGMXVWWKHWKHPH
2I FRXUVH LI \RX ZLVK WR UHDOO\ JHW FUHDWLYH \RX FDQ HYHQ FUHDWH \RXU RZQ FXVWRP
WKHPHKRZHYHUWKDWLVRXWVLGHWKHVFRSHRIWKLVERRN

See Also
7KHPLQJ7RROEDUV

Detecting the Device’s Network Status


Problem
<RX ZDQW WR UHWULHYH RU VHQG GDWD XVLQJ WKH GHYLFH¦V QHWZRUN FRQQHFWLRQ IURP WKH
DSSOLFDWLRQ KRZHYHU WKH DSSOLFDWLRQ GRHVQ¦W NQRZ ZKHWKHU WKH XVHU KDV QHWZRUN
DFFHVV

Solution
%HIRUH\RXDWWHPSWWRDFFHVVFRQWHQWIURPWKH,QWHUQHWLW¦VLPSRUWDQWWRHQVXUHWKDW
WKHXVHUKDV,QWHUQHWDFFHVV7KHDSSVWRUHVZRQ¦WDFFHSWDSSOLFDWLRQVWKDWGRQ¦WGLVSOD\
VWDQGDUGHUURUPHVVDJHVRUZDUQLQJVZKHQWKHXVHULVQRWFRQQHFWHGWRWKH,QWHUQHW
DQGFRQWHQWFDQQRWEHUHWULHYHG
7KH3KRQH*DS$3,H[SRVHVDFRQQHFWLRQW\SHYDULDEOHWKDWGHWHFWVWKHGHYLFH¦VFXUUHQW
QHWZRUNVWDWXV6HYHUDOFRQVWDQWVDUHDYDLODEOHWKDWSURYLGHIXUWKHUGHWDLOUHJDUGLQJWKH
GHYLFH¦VQHWZRUNVWDWXVDOORZLQJIRUSRWHQWLDOFRQWHQWVFDOLQJIRUXVHUVRQDVORZHU
QHWZRUNRUZLWKORZEDQGZLGWKSODQV

Discussion
%\HQVXULQJWKDWWKHYDULDEOH navigator.network.connection.typeLVQRWHTXDOWRWKH
FRQVWDQWConnection.NONEWKHDSSOLFDWLRQLVDEOHWRGHWHUPLQHWKDWWKHGHYLFHLVDFWLYHO\
FRQQHFWHG WR WKH ,QWHUQHW 7KH IROORZLQJ H[DPSOH H[WHQGV WKH SUHYLRXVO\ FUHDWHG

8 | The Recipes

www.it-ebooks.info
FRPPRQMVILOHWRDGGDQHZIXQFWLRQWKDWSHUIRUPVWKLVFKHFNDQGVHWVDJOREDOYDULDEOH
WRWUXH7KLVIXQFWLRQLVFDOOHGIURPWKHonDeviceReadyIXQFWLRQ
// Global variable that will tell us whether PhoneGap is ready
var isPhoneGapReady = false;

// Store the current network status


var isConnected = false;

function init() {
// Add an event listener for deviceready
document.addEventListener("deviceready",
onDeviceReady, false);
}

function onDeviceReady() {
// set to true
isPhoneGapReady = true;

// detect for network access


networkDetection();
}

function networkDetection() {
if (isPhoneGapReady) {
// as long as the connection type is not none,
// the device should have Internet access
if (navigator.network.connection.type != Connection.NONE) {
isConnected = true;
}
}
}

// Set an onload handler to call the init function


window.onload = init;

7KLVFRGHDOORZVIXWXUHIXQFWLRQVWRSHUIRUPDFKHFNWRHQVXUHWKDWWKHGHYLFHLVFRQ
QHFWHGWRWKH,QWHUQHWSULRUWRPDNLQJDQ\H[WHUQDOFDOOV7KHQH[WH[DPSOHZLOOXSGDWH
WKHnetworkDetectionIXQFWLRQWRVHWDQHZJOREDOYDULDEOHLQGLFDWLQJZKHWKHUWKHDS
SOLFDWLRQLVFRQQHFWHGWRDKLJKVSHHGFRQQHFWLRQ
// Global variable that will tell us whether PhoneGap is ready
var isPhoneGapReady = false;

// Store the current network status


var isConnected = false;
var isHighSpeed = false;

function init() {
// Add an event listener for deviceready
document.addEventListener("deviceready",
onDeviceReady, false);
}

function onDeviceReady() {

Detecting the Device’s Network Status | 9

www.it-ebooks.info
// set to true
isPhoneGapReady = true;

// detect for network access


networkDetection();
}

function networkDetection() {
if (isPhoneGapReady) {
// as long as the connection type is not none,
// the device should have Internet access
if (navigator.network.connection.type != Connection.NONE) {
isConnected = true;
}

// determine whether this connection is high-speed


switch (navigator.network.connection.type) {
case Connection.UNKNOWN:
case Connection.CELL_2G:
isHighSpeed = false;
break;
default:
isHighSpeed = true;
break;
}
}
}

// Set an onload handler to call the init function


window.onload = init;

1RZZKHQ\RXZLVKWRORDGFRQWHQWIURPDQH[WHUQDOVHUYHUE\GHWHUPLQLQJZKHWKHU
WKHXVHUKDVDORZVSHHGFRQQHFWLRQ\RXFDQVHUYHORZHUEDQGZLGWKFRQWHQWWRHQVXUH
DIDVWHUORDGWLPH,QWKHSUHYLRXVH[DPSOHD*RUXQNQRZQFRQQHFWLRQW\SHGHWHU
PLQHVORZVSHHG7KLVH[DPSOHFDQEHDOWHUHGWRUHFRJQL]HRWKHUFRQQHFWLRQW\SHVVXFK
DV*:L)LHWFDVW\SHVRIORZVSHHGFRQQHFWLRQ

See Also
&RPSDULVRQRI0RELOH3KRQH:LUHOHVV&RQQHFWLRQV

Detecting When the Network Status Changes


Problem
,Q£'HWHFWLQJWKH'HYLFH¦V1HWZRUN6WDWXV¤RQSDJH\RXGHWHFWHGWKDWWKHXVHUKDG
QHWZRUNDFFHVVZKHQWKHDSSOLFDWLRQILUVWORDGHGKRZHYHULQWKHWLPHVLQFHWKLVZDV
LQLWLDOO\GHWHFWHGWKHDSSOLFDWLRQLVXQVXUHZKHWKHUWKHXVHUVWLOOKDVFRQQHFWLYLW\SULRU
WRPDNLQJWKHILUVWQHWZRUNUHTXHVW

10 | The Recipes

www.it-ebooks.info
Solution
$VDXVHUWUDYHOVZLWKKLVRUKHUGHYLFHWKHQHWZRUNVWDWXVPLJKWFKDQJHEHFRPLQJ
HLWKHUDFWLYHRULQDFWLYH,I\RXUDSSOLFDWLRQLVQHWZRUNVHQVLWLYHLW¦VLPSRUWDQWWRWUDFN
WKHVHFKDQJHV<RXPD\QHHGWRDOHUWWKHXVHURULPSOHPHQWDV\QFV\VWHPWRPDLQWDLQ
DUHFRUGRIWKHFKDQJHVWKHXVHUPDNHVXQWLOWKHQHWZRUNEHFRPHVDYDLODEOHDJDLQ
7KH 3KRQH*DS $3, H[SRVHV D YDULHW\ RI HYHQWV IRU ZKLFK DQ DSSOLFDWLRQ FDQ OLVWHQ
WKURXJKDVWDQGDUG'20HYHQWOLVWHQHU7ZRRIWKHVHHYHQWVDUHRQOLQHDQGRIIOLQH
ZKLFKDUHWULJJHUHGZKHQWKHGHYLFH¦VQHWZRUNVWDWXVFKDQJHV

$V GLVFXVVHG LQ WKH ILUVW UHFLSH FXVWRP HYHQWV DUH QRW VXSSRUWHG E\
%ODFN%HUU\GHYLFHVROGHUWKDQYHUVLRQ,I\RXZLVKWRVXSSRUWWKH
HYHQWVZHPDQLSXODWHLQWKLVUHFLSHWKHEHVWVROXWLRQZRXOGEHWRLP
SOHPHQWDVLPLODULQWHUYDOWLPHUWKDWFKHFNVWKHGHYLFH¦VQHWZRUNVWDWXV
IRU FKDQJHV PDQXDOO\ 8QIRUWXQDWHO\ WKDW¦V ERWK SURJUDPPDWLFDOO\
FRPSOH[DQGDGUDLQRQWKHGHYLFH

Discussion
,QWKHIROORZLQJH[DPSOHWKHonDeviceReadyIXQFWLRQZLOOEHXSGDWHGWRDGGWZRHYHQW
OLVWHQHUVonlineDQGoffline:KHQWKHHYHQWILUHVDIXQFWLRQZLOOEHFDOOHGWKDWZLOO
DOWHUWKHSUHYLRXVO\FUHDWHGJOREDOYDULDEOH isConnected7KLVZLOOEHGRQHLQVLGHWKH
H[LVWLQJFRPPRQMVILOH
// Global variable that will tell us whether PhoneGap is ready
var isPhoneGapReady = false;

// Store the current network status


var isConnected = false;
var isHighSpeed = false;
var internetInterval;

function init() {
// Add an event listener for deviceready
document.addEventListener("deviceready",
onDeviceReady, false);
}

function onDeviceReady() {
// set to true
isPhoneGapReady = true;

// detect for network access


networkDetection();

// attach events for online and offline detection


document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
}

Detecting When the Network Status Changes | 11

www.it-ebooks.info
function networkDetection() {
if (isPhoneGapReady) {
// as long as the connection type is not none,
// the device should have Internet access
if (navigator.network.connection.type != Connection.NONE) {
isConnected = true;
}

// determine if this connection is high speed or not


switch (navigator.network.connection.type) {
case Connection.UNKNOWN:
case Connection.CELL_2G:
isHighSpeed = false;
break;
default:
isHighSpeed = true;
break;
}
}
}

function onOnline() {
isConnected = true;
}

function onOffline() {
isConnected = false;
}

// Set an onload handler to call the init function


window.onload = init;

$V,PHQWLRQHGHDUOLHUWKLVH[DPSOHZRQ¦WZRUNIRUROGHUYHUVLRQVRI%ODFN%HUU\EH
FDXVH RI WKH LQDELOLW\ WR VXSSRUW FXVWRP HYHQWV ,I \RX ZLVK WR VXSSRUW WKHVH ROGHU
YHUVLRQVWKHIROORZLQJH[DPSOHFRQWDLQVDGGLWLRQDOFRGHWKDWZLOOVHWDQLQWHUYDOWR
FKHFNZKHWKHUWKHQHWZRUNFRQQHFWLRQKDVFKDQJHGHYHU\VHFRQGV<RXFDQDOWHUWKH
QXPEHURIPLOOLVHFRQGVLQ\RXUFRGHLI\RXZLVKWRLQFUHDVHRUGHFUHDVHWKHIUHTXHQF\
function onDeviceReady() {
window.clearInterval(intervalID);

// set to true
isPhoneGapReady = true;

// detect for network access


networkDetection();

// attach events for online and offline detection


document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);

// set a timer to check the network status


internetInterval = window.setInterval(function() {
if (navigator.network.connection.type != Connection.NONE) {

12 | The Recipes

www.it-ebooks.info
onOnline();
} else {
onOffline();
}
}, 5000);
}

+HUHLQVLGHRIWKHifVWDWHPHQWWKDWFKHFNVWKHQHWZRUNFRQQHFWLRQ,DPFDOOLQJWKH
SUHYLRXVO\ FUHDWHG onOnline DQG onOffline IXQFWLRQV LQVWHDG RI MXVW FKDQJLQJ WKH
isConnectedYDULDEOH%\GRLQJWKLV,DOORZIXWXUHFKDQJHVWRWKRVHIXQFWLRQVWRDGG
DGGLWLRQDOIXQFWLRQDOLW\ZLWKRXWFKDQJLQJFRGHLQPXOWLSOHVSRWV

,QVWHDGRISHUIRUPLQJDQLQWHUYDOFKHFN\RXFDQFUHDWHDIXQFWLRQWKDW
FKHFNVWKHFRQQHFWLRQW\SHLPPHGLDWHO\EHIRUHH[HFXWLQJDUHTXHVWWKDW
UHTXLUHVDQHWZRUNFRQQHFWLRQ

Executing a Callback Function Once the Device Is Ready


Problem
$IWHUDSDJHKDVORDGHG\RXZLOOZDQWWRH[HFXWHVRPH-DYD6FULSWFRGHLPPHGLDWHO\
ZLWKRXWLQYRNLQJLWPDQXDOO\HDFKWLPHLQ\RXU-DYD6FULSWFRGH

Solution
%HFDXVH+70/GRHVQ¦WDOORZIRUDORWRIG\QDPLFIHDWXUHVDORWRIFRGHQHHGVWREH
GXSOLFDWHG7RPLQLPL]HWKHSDJHORDGWLPHV\RXVKRXOGORDGWKHPLQLPDODPRXQWRI
FRQWHQWHDFKWLPHZKLOHUHXVLQJDVPXFKFRGHDV\RXFDQ7KHFRPPRQMV-DYD6FULSW
ILOHPXVWEHNHSWOLJKWZHLJKWDQGDGGLWLRQDO-DYD6FULSWILOHVVKRXOGEHFUHDWHGIRURWKHU
QHZIXQFWLRQDOLW\+RZHYHUWKHUHFXUUHQWO\LVQRSURFHVVWRDOORZIRUDGGLWLRQDOIXQF
WLRQFDOOVRQFHWKHDSSOLFDWLRQKDVGHWHUPLQHGWKDWWKHGHYLFHLVUHDG\
<RXFDQXSGDWHWKHFRPPRQMV-DYD6FULSWILOHZLWKDQDXWRPDWLFFDOOEDFNIXQFWLRQWKDW
ZLOOEHH[HFXWHGRQFHWKHFRPPRQFRGHWRGHWHFWWKHGHYLFHW\SHQHWZRUNFRQQHFWLRQ
HWFKDVILQLVKHGZRUNLQJ7KLVZLOOHQDEOH\RXWRXVHWKHVDPHSURFHVVLQPDQ\IXWXUH
UHFLSHV

Discussion
%HFDXVHWKHDSSOLFDWLRQLVXVLQJM4XHU\PRELOH\RXPXVWUHRUJDQL]HVRPHRIWKHH[
LVWLQJFRGHLQRUGHUWRLPSURYHFRGHORDGLQJ:KHQ\RXQDYLJDWHEHWZHHQSDJHVXVLQJ
M4XHU\PRELOHLWSHUIRUPVWKHUHTXHVWYLD$-$;DQGVWULSVDOORIWKHFRQWHQWIURPWKH
+70/ILOH XQOHVVLWLVZLWKLQD divWDJWKDWFRQWDLQVD data-roleRIW\SHSDJH 7KLV

Executing a Callback Function Once the Device Is Ready | 13

www.it-ebooks.info
PHDQVWKDWWKHSUHYLRXVwindow.onloadHYHQWZLOOQRORQJHUWULJJHU,QVWHDGDQHZHYHQW
WKDWLVSURYLGHGE\WKHM4XHU\PRELOHOLEUDU\ZLOOEHXVHG
7KHILUVWWKLQJWRQRWHLVWKDWWKHLQGH[KWPOSDJHIURP£&UHDWLQJD3HUVLVWHQW1DYLJDWLRQ
6\VWHP¤RQSDJHUHTXLUHVVRPHUHIRUPDWWLQJDVIROORZV
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<link rel="stylesheet"
href="css/jquery.mobile-1.0rc1.min.css" />
<script type="text/javascript" charset="utf-8"
src="scripts/phonegap-1.0.0.js"></script>
</head>
<body>
<div data-role="page" id="index-page">
<h1>Hello World!</h1>

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html"
class="ui-btn-active">Home</a></li>
<li><a href="about.html">About</a></li>
</ul>
</div>
</div>
</div>

<script type="text/javascript" charset="utf-8"


src="scripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript" charset="utf-8"
src="scripts/jquery.mobile-1.0rc1.min.js"></script>
<script type="text/javascript" charset="utf-8"
src="scripts/common.js"></script>
</body>
</html>

6HYHUDOWKLQJVKDYHFKDQJHGLQWKLVFRGH0RVWRIWKH-DYD6FULSWILOHVKDYHEHHQPRYHG
RXWRIWKHheadWDJ,¦YHOHIWWKHPDLQ3KRQH*DSILOHWKHUHWRHQVXUHWKDWLWORDGVFRP
SOHWHO\EHIRUHWKHSDJHGRHVEHFDXVHDQ\WKLQJSODFHGLQVLGHWKH headWDJPXVWIXOO\
ILQLVKORDGLQJEHIRUH\RXFRQWLQXH1H[WDQHZdivWDJZDVDGGHGZLWKDdata-roleRI
W\SHpage)LQDOO\WKHSUHYLRXV-DYD6FULSWILOHVKDYHEHHQPRYHGWRWKHERWWRPDQGWKH
RUGHUKDVEHHQDOWHUHG7KHVHKDYHDOVREHHQSODFHGRXWVLGHRIWKHSDJHdivWDJEHFDXVH
WKH\GRQRWQHHGWREHORDGHGDJDLQLIWKHXVHUQDYLJDWHVEDFNWRWKHLQGH[SDJH7KH
RUGHURIWKHILOHVZDVDOWHUHGEHFDXVHLQWKHQH[WH[DPSOHWKHFRPPRQMVILOHZLOOEH
XSGDWHGWRXVHHOHPHQWVRIM4XHU\DQGWKHPRELOHOLEUDU\ZKLFKPXVWORDGILUVW
:LWKLQWKHQH[WH[DPSOHLVDQXSGDWHGFRPPRQMVILOH,WFRQWDLQVDOORIWKHFRGHIURP
WKHILUVWVHYHUDOUHFLSHVWKDWSHUIRUPVWKHIROORZLQJRSHUDWLRQVGHYLFHUHDG\GHYLFH
GHWHFWLRQDQGQHWZRUNGHWHFWLRQDVZHOODVWKHQHZFDOOEDFNIHDWXUH7KHNH\REMHFWLYH

14 | The Recipes

www.it-ebooks.info
RIWKLVH[SDQGHGFRGHLVWRDOORZ\RXWRUXQFXVWRPFRGHWLHGWRWKHQDPHRIDSDUWLFXODU
SDJHZKHQWKDWSDJHORDGV
// Global variable that will tell us whether PhoneGap is ready
var isPhoneGapReady = false;

// Default all phone types to false


var isAndroid = false;
var isBlackberry = false;
var isIphone = false;
var isWindows = false;

// Store the device's uuid


var deviceUUID;

// Store the current network status


var isConnected = false;
var isHighSpeed;
var internetInterval;

var currentUrl;

function init(url) {
if (typeof url != 'string') {
currentUrl = location.href;
} else {
currentUrl = url;
}

if (isPhoneGapReady) {
onDeviceReady();
} else {
// Add an event listener for deviceready
document.addEventListener("deviceready",
onDeviceReady, false);
}
}

function onDeviceReady() {
// set to true
isPhoneGapReady = true;

deviceUUID = device.uuid;

// detect the device's platform


deviceDetection();

// detect for network access


networkDetection();

// execute any events at start up


executeEvents();

// execute a callback function


executeCallback();

Executing a Callback Function Once the Device Is Ready | 15

www.it-ebooks.info
}

function executeEvents() {
if (isPhoneGapReady) {
// attach events for online and offline detection
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);

// set a timer to check the network status


internetInterval = window.setInterval(function() {
if (navigator.network.connection.type != Connection.NONE) {
onOnline();
} else {
onOffline();
}
}, 5000);
}
}

function executeCallback() {
if (isPhoneGapReady) {
// get the name of the current html page
var pages = currentUrl.split("/");
var currentPage = pages[pages.length - 1].
slice(0, pages[pages.length - 1].indexOf(".html"));

// capitalize the first letter and execute the function


currentPage = currentPage.charAt(0).toUpperCase() +
currentPage.slice(1);

if (typeof window['on' + currentPage + 'Load'] ==


'function') {
window['on' + currentPage + 'Load']();
}
}
}

function deviceDetection() {
if (isPhoneGapReady) {
switch (device.platform) {
case "Android":
isAndroid = true;
break;
case "Blackberry":
isBlackberry = true;
break;
case "iPhone":
isIphone = true;
break;
case "WinCE":
isWindows = true;
break;
}
}
}

16 | The Recipes

www.it-ebooks.info
function networkDetection() {
if (isPhoneGapReady) {
// as long as the connection type is not none,
// the device should have Internet access
if (navigator.network.connection.type != Connection.NONE) {
isConnected = true;
}

// determine if this connection is high speed or not


switch (navigator.network.connection.type) {
case Connection.UNKNOWN:
case Connection.CELL_2G:
isHighSpeed = false;
break;
default:
isHighSpeed = true;
break;
}
}
}

function onOnline() {
isConnected = true;
}

function onOffline() {
isConnected = false;
}

// This gets called by jQuery mobile when the page has loaded
$(document).bind("pageload", function(event, data) {
init(data.url);
});

// Set an onload handler to call the init function


window.onload = init;

7KHUHLVTXLWHDELWKDSSHQLQJLQWKHSUHFHGLQJFRGH,ZLOOVWDUWDWWKHERWWRPZLWKWKH
WZRHYHQWVWKDWFDOOWKHinitIXQFWLRQ7KHwindow.onloadFRGHUHPDLQVDVLVDQGZLOO
EHFDOOHGZKHQWKHDSSOLFDWLRQILUVWORDGV%\ELQGLQJWKHpageloadHYHQWWRWKHGRFX
PHQW,HQVXUHWKDWHDFKWLPHDXVHUFOLFNVDQHZOLQNWKLVHYHQWZLOOILUHZKHQWKDWSDJH
KDVILQLVKHGORDGLQJ,WLVDOVRSDVVLQJWKHFXUUHQW85/WRWKHXSGDWHGinitIXQFWLRQ
7KLVZLOOEHXVHGIRULPSOHPHQWLQJWKHFDOOEDFNIXQFWLRQ
7KHinitIXQFWLRQKDVEHHQXSGDWHGWRDFFHSWWKLVQHZurlSDUDPHWHU+RZHYHUVLQFH
WKLV SDUDPHWHU LV QRW SDVVHG LQ E\ WKH window.onload HYHQW WKH FRGH FKHFNV WR VHH
ZKHWKHU LW LV D VWULQJ :KHQ D VWULQJ LV QRW GHWHFWHG LH RQ ILUVW ORDG  WKH loca
tion.hrefLVXVHGDQGVWRUHGLQWKH currentUrlJOREDOYDULDEOH7KHQLIWKHYDULDEOH
isPhoneGapReadyLVDOUHDG\VHWDQGWUXHWKHUHLVQRQHHGWRDGGWKHOLVWHQHUDQGZDLW
VRLWMXVWFDOOVWKHonDeviceReadyIXQFWLRQ

Executing a Callback Function Once the Device Is Ready | 17

www.it-ebooks.info
7KH onDeviceReadyIXQFWLRQKDVEHHQVOLJKWO\UHRUJDQL]HGDQGVRPHRIWKHSUHYLRXV
ZRUNKDVEHHQPRYHGLQWRQHZIXQFWLRQVIRUODWHUH[SDQVLRQLQFOXGLQJWKHQHZO\DGGHG
executeCallbackIXQFWLRQ
7KHexecuteCallbackIXQFWLRQWDNHVWKH currentUrlYDULDEOHDQGVSOLWVLWLQWRSDUWVWR
EHDEOHWRUHWULHYHMXVWWKHILOHQDPHHJWKHLQGH[7KLVQDPHLVWKHQXVHGWRFKHFN
ZKHWKHUWKHUHLVDIXQFWLRQFDOOHGonIndexLoad,IWKLVIXQFWLRQH[LVWVLWLVH[HFXWHG
:KHQ \RX DGG IXWXUH SDJHV \RX FDQ DOVR DGG QHZ IXQFWLRQV WKDW ZLOO EH H[HFXWHG
DXWRPDWLFDOO\RQFHWKHSDJHORDGV7KHVHZLOOSHUIRUPDQ\DGGLWLRQDOSURFHVVLQJUH
TXLUHGE\WKDWSDJH)RULQVWDQFHLI\RXDGGDQ onAboutLoadIXQFWLRQWKHDSSZLOO
H[HFXWHLWZKHQDERXWKWPOKDVILQLVKHGORDGLQJ

See Also
M4XHU\0RELOH(YHQWV

Detecting When the App Is Moved to the Background or


Foreground
Problem
<RXU DSSOLFDWLRQ QHHGV WR SHUIRUP D VSHFLILF DFWLRQ ZKHQ LW LV PRYHG HLWKHU WR WKH
EDFNJURXQGRUWKHIRUHJURXQG

Solution
7KH3KRQH*DS$3,SURYLGHVWZRHYHQWVpauseDQGresumeWKDWJHWWULJJHUHGZKHQWKH
DSSOLFDWLRQLVSODFHGLQWKHEDFNJURXQGDQGIRUHJURXQGUHVSHFWLYHO\%\DGGLQJD'20
OLVWHQHUIRUWKHVHHYHQWVWKHDSSOLFDWLRQFDQUHVSRQGWRWKHPDFFRUGLQJO\HJVWRS
UHWULHYLQJXSGDWHVIURPDQH[WHUQDOVRXUFHVDYHWKHSURJUHVVRIDJDPHHWF

Discussion
7KHUHLVRQHILQDOXSGDWHWKDWQHHGVWRRFFXUWRWKHDVVHWVZZZVFULSWVFRPPRQMVILOH
7KHexecuteEventsIXQFWLRQUHTXLUHVXSGDWLQJWROLVWHQIRUWKHpauseDQGresumeHYHQWV
WKDW3KRQH*DSH[HFXWHVHDFKWLPHWKHDSSOLFDWLRQLVPRYHGWRWKHEDFNJURXQGDQG
IRUHJURXQGUHVSHFWLYHO\
function executeEvents() {
if (isPhoneGapReady) {
// attach events for online and offline detection
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);

18 | The Recipes

www.it-ebooks.info
// attach events for pause and resume detection
document.addEventListener("pause", onPause, false);
document.addEventListener("resume", onResume, false);

// set a timer to check the network status


internetInterval = window.setInterval(function() {
if (navigator.network.connection.type != Connection.NONE) {
isOnline();
} else {
isOffline();
}
}, 5000);
}
}

$VPHQWLRQHGSUHYLRXVO\FXVWRPHYHQWVZLOOQRWZRUNRQROGHUYHUVLRQV
RI%ODFN%HUU\

1RZ onPauseDQG onResumeIXQFWLRQVFDQEHFUHDWHG7KH onPauseIXQFWLRQLVDJRRG


SODFHWRVWRSDQ\WLPHULQWHUYDOVRUZDWFKHVWKDWDUHLQSODFHDVZHOODVVHWisPhoneGap
ReadyWRIDOVH
function onPause() {
isPhoneGapReady = false;

// clear the Internet check interval


window.clearInterval(internetInterval);
}

7KHonResumeIXQFWLRQFDQUHLQVWDWHWKHOLVWHQLQJWKDWZDVVWRSSHGLQWKHonPauseIXQF
WLRQ
function onResume() {
// don't run if phonegap is already ready
if (isPhoneGapReady == false) {
init(currentUrl);
}
}

7KHonResumeIXQFWLRQFDOOVWKHinitIXQFWLRQZKLFKZLOOUHVHWDQ\LQWHUYDOVDQGZDWFKHV
DVZHOODVH[HFXWHWKHFDOOEDFNIXQFWLRQRQWKHSDJHWRUHIUHVKWKHFRQWHQW

:KHQ,ZDVWHVWLQJWKLVFRGH,IRXQGWKHonResumeIXQFWLRQFRQVWDQWO\
ILULQJ ZKLFK LV ZK\ WKH init IXQFWLRQ FDOO LV ZUDSSHG ZLWKLQ DQ if
VWDWHPHQWFKHFNLQJIRUisPhoneGapReady == false

Detecting When the App Is Moved to the Background or Foreground | 19

www.it-ebooks.info
Using the GPS and Displaying a Position on a Map
Problem
<RXZDQWWRUHWULHYHWKHGHYLFH¦VFXUUHQW*36ORFDWLRQDQGSODFHDPDUNHULQGLFDWLQJ
WKHFXUUHQWSRVLWLRQRQDPDS

Solution
2QHRIWKHPRVWFRPPRQIXQFWLRQDOLWLHVLQDQ\PRELOHDSSOLFDWLRQLVWRUHWULHYHWKH
GHYLFH¦VORFDWLRQWKURXJK*36RU:L)LGHWHFWLRQDQGWKHQSORWWKHFXUUHQWSRVLWLRQRQ
DPDS
7RUHDGWKHGHYLFH¦VFXUUHQW*36ORFDWLRQ3KRQH*DSSURYLGHVWKUHHXVHIXOIXQFWLRQV
getCurrentPositionwatchPositionDQGclearWatch7KHVHFRQGIXQFWLRQSURYLGHVIUH
TXHQWXSGDWHVWRWKHORFDWLRQDVWKHXVHUPRYHV
7KHGHYLFH¦VFXUUHQWORFDWLRQLVUHWXUQHGYLD-DYD6FULSWREMHFWV7KLVLQIRUPDWLRQFRQ
WDLQVDWLPHVWDPSRIZKHQWKHFRRUGLQDWHVZHUHUHWULHYHGDQGDQREMHFWWKDWFRQWDLQV
DOORIWKHSHUWLQHQWLQIRUPDWLRQLQWKHFRRUGLQDWHV7KLVHQDEOHVWKHXVHUWRSORWWKH
ORFDWLRQRQDPDS ODWLWXGHORQJLWXGHHWF 
7KH3KRQH*DS$3,GRHVQ¦WSURYLGHQDWLYHVXSSRUWIRUPDSVVRWKHVLPSOHVWVROXWLRQ
WRHQVXUHWKDW\RXVXSSRUWWKHPRVWSODWIRUPVLVWRLQWHJUDWH*RRJOH0DSV$3,YLDWKHLU
-DYD6FULSW$3,:KLOHWKLVZLOOEHDOLWWOHELWVORZHUDVLWUHTXLUHVWUDQVIHUULQJWKHPDSV
RYHUWKHQHWZRUNLWLVIDUOHVVZRUNWKDQH[WHQGLQJWKHDSSOLFDWLRQYLDDSOXJLQIRUWKH
YDULRXVVPDUWSKRQHV

Discussion
7R EHJLQ \RX PXVW FUHDWH D QHZ +70/ ILOH FDOOHG PDSKWPO LQVLGH RI \RXU DVVHWV
ZZZGLUHFWRU\7KLVILOHZLOOFRQWDLQVRPHEDVLF+70/WRGLVSOD\WKHPHQXDVZHOO
DVDSODFHKROGHUIRU*RRJOH0DSV$3,
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<meta name="viewport" content="initial-scale=1.0,
user-scalable=no" />
</head>
<body>
<div data-role="page" id="map-page">
<div id="map_canvas"
style="width: 300px; height: 300px"></div>

<div data-role="footer" data-position="fixed">


<div data-role="navbar">

20 | The Recipes

www.it-ebooks.info
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="map.html"
class="ui-btn-active">Map</a></li>
</ul>
</div>
</div>

<script type="text/javascript" charset="utf-8"


src="scripts/map.js"></script>
</div>
</body>
</html>

7KH QDYEDU KDV EHHQ XSGDWHG WR UHSODFH WKH WHPSRUDU\ $ERXW H[DPSOH ZLWK D QHZ
0DSOLQNZKLFKLVVHWWRDFWLYHLQWKLVILOH7KLVVKRXOGEHXSGDWHGLQ\RXUindex.html
DVZHOO1HDUWKHERWWRPRIWKLVILOHDQHZ-DYD6FULSWILOHLVLQFOXGHGFDOOHGPDSMV7KLV
ILOHVKRXOGEHFUHDWHGLQVLGHRI\RXUDVVHWVZZZVFULSWVGLUHFWRU\DQGLWZLOOFRQWDLQWKH
FRUHRIWKHIXQFWLRQDOLW\
function onMapLoad() {
if (isConnected) {
// load the google api
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src",
"http://maps.googleapis.com/maps/api/js?sensor=true&callback=" +
"getGeolocation");
document.getElementsByTagName("head")[0].
appendChild(fileref);
} else {
alert("Must be connected to the Internet");
}
}

function getGeolocation() {
// get the user's gps coordinates and display map
var options = {
maximumAge: 3000,
timeout: 5000,
enableHighAccuracy: true
};
navigator.geolocation.getCurrentPosition(loadMap,
geoError, options);
}

function loadMap(position) {
var latlng = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);

var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

Using the GPS and Displaying a Position on a Map | 21

www.it-ebooks.info
var mapObj = document.getElementById("map_canvas");
var map = new google.maps.Map(mapObj, myOptions);

var marker = new google.maps.Marker({


position: latlng,
map: map,
title:"You"
});
}

function geoError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}

4XLWHDORWLVKDSSHQLQJLQWKHSUHFHGLQJH[DPSOH:KHQWKHSDJHKDVILQLVKHGORDGLQJ
WKDQNVWRWKHFDOOEDFNIXQFWLRQLPSOHPHQWHGLQWKHSUHYLRXVUHFLSHonMapLoadLVFDOOHG
DXWRPDWLFDOO\RQFHWKHSDJHLVORDGHG%HFDXVHWKHM4XHU\PRELOHOLEUDU\LVEHLQJXVHG
WKH*RRJOH$3,-DYD6FULSWILOHPXVWEHLQFOXGHGG\QDPLFDOO\RWKHUZLVHLWGRHVQ¦WJHW
ORDGHGSURSHUO\YLDWKH$-$;UHTXHVW

,QFDVH\RXPLVVHGLWLQ£([HFXWLQJD&DOOEDFN)XQFWLRQ2QFHWKH'HYLFH
,V5HDG\¤RQSDJHIRUVXEVHTXHQWSDJHVORDGHGYLDWKHM4XHU\0R
ELOH$3,DVLPSOHwindow.onloadZLOOQRWZRUNEHFDXVHSDJHVDUHORDGHG
YLD$-$;,QVWHDG\RXQHHGWRELQGDQHYHQWIRUSDJHORDGWKDWLVFDOOHG
E\ WKH OLEUDU\ RQFH WKH SDJH KDV ILQLVKHG ORDGLQJ $(docu
ment).bind("pageload", onMapLoad);

2QFHWKH*RRJOH$3,LVORDGHGWKHgetGeolocationFDOOEDFNIXQFWLRQLVH[HFXWHG7KLV
IXQFWLRQ XVHV WKH 3KRQH*DS $3, WR UHWULHYH WKH XVHU¦V FXUUHQW ORFDWLRQ 7KH naviga
tor.geolocation.getCurrentPosition IXQFWLRQ DFFHSWV WKUHH SDUDPHWHUV WKH VXFFHVV
IXQFWLRQWKDWLVFDOOHGRQFHWKHORFDWLRQLVUHWULHYHGDQHUURUIXQFWLRQWRLQYRNHLIWKH
JHRORFDWLRQFRXOGQRWEHUHWULHYHGDQGILQDOO\VRPH-621RSWLRQV
:KHQ WKH JHRORFDWLRQ LV VXFFHVVIXOO\ UHFHLYHG WKH FRGH FDOOV WKH loadMap IXQFWLRQ
ZKLFKDFFHSWVRQHSDUDPHWHUFDOOHGposition7KLVSDUDPHWHUFRQWDLQVWKHODWLWXGHDQG
ORQJLWXGHDVZHOODVVHYHUDORWKHUSURSHUWLHVZKLFKDUHXVHGWRFHQWHUWKHPDSDQG
FUHDWHDPDUNHU7KHUHPDLQGHURIWKHH[DPSOHLQFOXGHVVRPHRIWKHVDPSOHFRGHSUR
YLGHGE\*RRJOHWRGHPRQVWUDWHWKHXVHRIWKHLU$3,:KHQ\RXUXQWKLVH[DPSOHD
QHZPDSZLOOEHORDGHGLQWRWKH map_canvas divWDJDQGZLOOFHQWHURQ\RXUFXUUHQW
ORFDWLRQ$OVRDPDUNHUZLOOEHFUHDWHGLGHQWLI\LQJZKHUH\RXDUH

7KLVIHDWXUHPLJKWQRWZRUNFRUUHFWO\LQDOOVLPXODWRUVDQGDQDFWXDO
GHYLFHPD\EHQHHGHG

22 | The Recipes

www.it-ebooks.info
See Also
*RRJOH0DSV$3,

Using the Compass to Help the User Navigate


Problem
<RXZDQWWRGHWHFWWKHGLUHFWLRQLQZKLFKWKHGHYLFHLVFXUUHQWO\SRLQWLQJ

Solution
L26$QGURLGDQGVRPH:LQGRZVGHYLFHVVXSSRUWDFRPSDVVWKDWZLOOWHOO\RXWKH
GLUHFWLRQWKHSKRQHLVSRLQWLQJLQZLWKDUDQJHRIWRGHJUHHV
3KRQH*DSSURYLGHVVHYHUDOIXQFWLRQVWKDWZRUNTXLWHVLPLODUO\WRWKH*36ORFDWLRQ
ZKHUH\RXFDQUHWULHYHWKHFXUUHQWGLUHFWLRQWKHGHYLFHLVSRLQWLQJLQGHJUHHV<RXFDQ
ZDWFKWKLVYDOXHDQG\RXUDSSOLFDWLRQZLOOUHFHLYHUHJXODUXSGDWHVRQLWVSRVLWLRQ%\
XVLQJ WKH navigator.compass.watchHeading RU navigator.compass.getCurrentHeading
IXQFWLRQV\RXZLOOUHFHLYHDmagneticHeadingYDULDEOHWKDWFRQWDLQVDYDOXHEHWZHHQ
DQGGHJUHHV

Discussion
7RGHPRQVWUDWHWKHFRPSDVVIXQFWLRQV,¦PJRLQJWRSXWWRJHWKHUDYHU\VLPSOH+70/
SDJHWKDWFRQWDLQVWZRLPDJHVDFRPSDVVDQGLWVQHHGOH7RVWDUWZLWK\RXQHHGDQHZ
+70/SDJHOHW¦VFDOOLWFRPSDVVKWPO<RXZLOOZDQWWRDGGDQHZPHQXLWHPRQ\RXU
H[LVWLQJ+70/SDJHVWROLQNWKHQHZSDJH
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="compass-page">
<div style="background:
url(images/compass.png) no-repeat">
<img id="needle" src="images/needle.png" />
</div>

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="map.html">Map</a></li>
<li><a href="compass.html"
class="ui-btn-active">Compass</a></li>

Using the Compass to Help the User Navigate | 23

www.it-ebooks.info
</ul>
</div>
</div>

<script type="text/javascript" charset="utf-8"


src="scripts/jQueryRotateCompressed.2.1.js"></script>
<script type="text/javascript" charset="utf-8"
src="scripts/compass.js"></script>
</div>
</body>
</html>

7KH+70/LVTXLWHVLPSOH,¦YHFUHDWHGDdivHOHPHQWWKDWFRQWDLQVWKHFRPSDVVDVD
EDFNJURXQGLPDJHDQGORDGVWKHQHHGOHLPDJHLQVLGHRILW$WWKHERWWRP,¦YHLQFOXGHG
WZRQHZ-DYD6FULSWILOHV7KHILUVWLVDOLEUDU\WKDWZLOOKHOSPHURWDWHWKHLPDJHLQP\
-DYD6FULSWFRGHLQWKHXSFRPLQJH[DPSOH7KHVHFRQGLVWKHQH[WILOHWKDWPXVWEH
FUHDWHGFRPSDVVMV
function onCompassLoad() {
var options = { frequency: 500 };
navigator.compass.watchHeading(rotateNeedle,
compassError, options);
}

function rotateNeedle(degree) {
$("#needle").rotate(degree);
}

function compassError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}

8VLQJWKHDXWRPDWLFFDOOEDFNWKHonCompassLoadIXQFWLRQ,¦YHFUHDWHGDZDWFKWRXS
GDWHWKHFRPSDVVHYHU\PLOOLVHFRQGVYLDD navigator.compass.watchHeadingIXQF
WLRQ(DFKWLPHDQXSGDWHLVUHFHLYHGWKH rotateNeedleIXQFWLRQLVFDOOHG8VLQJWKH
M4XHU\OLEUDU\,PHQWLRQHGHDUOLHU,URWDWHWKHQHHGOHE\WKHDQJOHRIWKHGHYLFH7KH
UHVXOWVRIdegreeLVDQXPEHUEHWZHHQDQG$VWKHGHYLFHURWDWHVDURXQGWKH
QHHGOHZLOOPRYHDVZHOOLQGLFDWLQJWKHFXUUHQWGLUHFWLRQ

7KLVIHDWXUHPLJKWQRWZRUNFRUUHFWO\LQDOOVLPXODWRUVDQGDQDFWXDO
GHYLFHPD\EHQHHGHG

See Also
M4XHU\5RWDWH3OXJ,Q

24 | The Recipes

www.it-ebooks.info
Using the Accelerometer to Detect Motion
Problem
<RXZDQWWRGHWHFWWKHPRWLRQRIWKHGHYLFHDVLWPRYHV

Solution
6LPLODUWRWKHFRPSDVVGHYLFHVUXQQLQJL26$QGURLGDQG%ODFN%HUU\DQGDERYH
DUHDEOHWRGHWHFWWKHGHYLFH¦VFXUUHQW[\DQG]D[LVPRYHPHQWV
7KUHHIXQFWLRQVH[LVWWKDWZRUNLQWKHVDPHZD\DVWKHFRPSDVVDQG*36ORFDWLRQ
ZKLFKDOORZ\RXWRUHWULHYHWKHFXUUHQW[\DQG]FRRUGLQDWHVWKURXJKWKHXVHRIWKH
accelerometer.getCurrentAcceleration IXQFWLRQ 7KH accelerometer.watchAccelera
tionIXQFWLRQDOORZV\RXWRUHFHLYHXSGDWHVRQWKHGHYLFH¦VSRVLWLRQZKLOHWKH accel
erometer.clearWatchIXQFWLRQDOORZV\RXWRWXUQRIIUHFHLYLQJWKHXSGDWHV

Discussion
7RGHPRQVWUDWHWKHDFFHOHURPHWHU,DPJRLQJWRXVHWKHQHZ+70/canvasWDJDQG
PDNHDQLPDJHRIDEDOOPRYHDURXQGZLWKWKHPRYHPHQWRIWKHGHYLFH7RVWDUWDQHZ
+70/SDJHPXVWEHFUHDWHGLQVLGHRIWKHDVVHWVZZZGLUHFWRU\DFFHOHURPHWHUKWPO
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="accelerometer-page">
<div data-role="header" data-position="inline">
<h1>Bouncing Ball</h1>
</div>

<canvas id="canvas" width="350" height="350"


style="border: 2px solid #000"></canvas>
<img id="ball" style="display: none" />

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="map.html">Map</a></li>
<li><a href="compass.html">Compass</a></li>
<li><a href="list.html">List</a></li>
<li><a href="accelerometer.html"
class="ui-btn-active">Accelerometer</a></li>
</ul>
</div>
</div>

Using the Accelerometer to Detect Motion | 25

www.it-ebooks.info
<script type="text/javascript" charset="utf-8"
src="scripts/accelerometer.js"></script>
</div>
</body>
</html>

7KHSUHFHGLQJFRGHGRHVWKUHHLPSRUWDQWWKLQJV,WFUHDWHVDQHZ canvasWDJZLWKWKH
,'RIFDQYDVFUHDWHVDQ imgWDJZLWKWKH,'RIEDOODQGLQFOXGHVDQHZDFFHOHURPH
WHUMV -DYD6FULSW ILOH 7KLV VFULSW VKRXOG QRZ EH FUHDWHG LQVLGH RI \RXU DVVHWVZZZ
VFULSWVGLUHFWRU\
var canvas;
var context;
var ball;

var prevX = 150;


var prevY = 150;
var offSet = 0.05;

var accelTimer;

function onAccelerometerLoad() {
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');

ball = document.getElementById('ball');
ball.onload = function() {
// once the ball image has loaded, start the watch
var options = { frequency: 100 };
accelTimer =
navigator.accelerometer.watchAcceleration(
moveBall, stopBall, options);
};
ball.src = "images/ball.png";
}

function moveBall(acceleration) {
var x = acceleration.x * 100;
var y = acceleration.y * 100;

var newX = x * offSet + (1 - offSet) * prevX;


var newY = y * offSet + (1 - offSet) * prevY;

prevX = newX;
prevY = newY;

// draw the ball


drawImage(newX, newY);
}

function stopBall(error) {
// clear the watch
navigator.accelerometer.clearWatch(accelTimer);

26 | The Recipes

www.it-ebooks.info
alert("Error detecting acceleration");
}

function drawImage(x, y) {
context.clearRect(0, 0, 350, 350);
context.drawImage(ball, 0, 0, 100, 81, x, y, 100, 81);
}

7KHSUHFHGLQJ-DYD6FULSWFUHDWHVVHYHQJOREDOYDULDEOHV7KHILUVWWKUHHZLOOEHXVHGWR
SHUIRUPWKHDQLPDWLRQDVWKH\FRQWDLQUHIHUHQFHVWRWKHFDQYDVWKHFDQYDV¦FRQWH[W
DQG ILQDOO\ WKH LPDJH RI WKH EDOO 7KH QH[W IRXU YDULDEOHV ZLOO EH XVHG LQVLGH RI WKH
moveBallIXQFWLRQWRKHOSFDOFXODWHWKHPRYHPHQWRIWKHEDOO7KHILQDOYDULDEOHZLOO
FRQWDLQDUHIHUHQFHWRWKHDFFHOHURPHWHUZDWFKZKLFKZLOOEHFOHDUHGLIWKHUHLVDQHUURU
,QVLGHRIWKHonAccelerometerLoadIXQFWLRQWKHUHIHUHQFHVWRWKHcanvascontextDQG
ballDUHLQLWLDOL]HG7KHVRXUFHRIWKHEDOOLPDJHLVDOVRVHWLW¦VDVLPSOH31*LPDJHRI
DWHQQLVEDOOWKDWLVSL[HOVE\SL[HOV:KHQWKHLPDJHRIWKHEDOOKDVVXFFHVVIXOO\
ILQLVKHG ORDGLQJ WKH navigator.accelerometer.watchAcceleration IXQFWLRQ SODFHV D
ZDWFKRQWKHDFFHOHURPHWHU7KHUHVXOWRIWKLVIXQFWLRQLVVWRUHGLQDJOREDOYDULDEOH
FDOOHG accelTimer7KLVYDULDEOHFRQWDLQVDUHIHUHQFHWRWKHLQWHUYDOWKDWLVFUHDWHGE\
3KRQH*DS,WFDQEHXVHGWRFOHDUWKHLQWHUYDOYLDWKHclearWatchIXQFWLRQDVZHGRLQ
WKHstopBallIXQFWLRQ7KLVPLJKWEHQHFHVVDU\LI\RXZLVKWRSDXVHWKHDFFHOHURPHWHU
GXULQJWKHDSSOLFDWLRQ
(YHU\PLOOLVHFRQGVWKHmoveBallIXQFWLRQZLOOEHFDOOHG7KLVIXQFWLRQUHFHLYHVRQH
SDUDPHWHUWKHaccelerationRIWKHGHYLFH7KHaccelerationLVDVWUXFWXUHWKDWFRQWDLQV
IRXUYDULDEOHVWKH[\]SRVLWLRQRIWKHGHYLFHDQGDWLPHVWDPSRIZKHQLWZDVUH
WULHYHG
7KHmoveBallIXQFWLRQZLOOXVHWKH[DQG\SRVLWLRQVWRFDOFXODWHKRZPXFKPRYHPHQW
KDV RFFXUUHG VLQFH WKH ODVW UHWULHYDO ,W ZLOO WKHQ SHUIRUP D FDOFXODWLRQ DQG FDOO WKH
drawImageIXQFWLRQZKLFKZLOOPRYHWKHEDOORQWKHVFUHHQ)LUVWdrawImageFOHDUVWKH
FDQYDV¦VVFUHHQWKHQLWGUDZVWKHLPDJHRIWKHEDOORQVFUHHQLQWKHQHZ[\FRRUGLQDWHV
WKDWZHUHFDOFXODWHGLQWKH moveBallIXQFWLRQ,I\RXZRXOGOLNHVRPHPRUHGHWDLORQ
WKHcontext.drawImageIXQFWLRQ\RXFDQUHDGWKLVDUWLFOH,ZURWHZKHQH[SHULPHQWLQJ
ZLWKWKHWDJWRFUHDWHDZDONLQJDQLPDWLRQXVLQJDQLPDJHVSULWH
,IWKHUHZDVDQHUURUGHWHFWLQJWKHDFFHOHUDWLRQWKH stopBallIXQFWLRQLVFDOOHG7KLV
IXQFWLRQFOHDUVWKHWLPHUZLWKWKH navigator.accelerometer.clearWatchIXQFWLRQ$Q
DOHUWGLDORJER[DSSHDUVDVZHOOWRLQIRUPWKHXVHURIWKHHUURU
7KLVFRGHLVDQH[FHOOHQWVWDUWWRFUHDWLQJDODE\ULQWKLQHJDPHXVLQJWKHGHYLFH¦VPRWLRQ
VHQVRUV

7KLVIHDWXUHPLJKWQRWZRUNFRUUHFWO\LQDOOVLPXODWRUVDQGDQDFWXDO
GHYLFHPD\EHQHHGHG

Using the Accelerometer to Detect Motion | 27

www.it-ebooks.info
Displaying Table-View Data
Problem
<RXKDYHDKLHUDUFKLFDOOLVWRILWHPVWKDW\RXZLVKWRGLVSOD\LQDWDEOHFDVFDGLQJVR
WKDWZKHQWKHXVHUVHOHFWVWKHRQHLWHPWKHWDEOHQDYLJDWHVWRDQRWKHUILOWHUHGOLVWRI
LWHPVXQWLOWKHXVHUUHFHLYHVWKHVSHFLILFGHWDLOYLHZ

Solution
:H¦OOXVHWKHM4XHU\PRELOHOLEUDU\WRGLVSOD\DVWDQGDUGORRNLQJWDEOHOLVWLQJRIGDWD
WKDWWKHXVHUFDQVFUROOXSRUGRZQE\VZLSLQJWKHLUILQJHU:KHQWKH\VHOHFWDQLWHP
LQWKHOLVWWKHOLEUDU\ZLOOWKHQILOWHUWKHOLVWRQFHWKH\FOLFNRQDVHFRQGLWHPWKHGHWDLO
SDJHZLOOEHGLVSOD\HG7KLVLVDFFRPSOLVKHGE\VRPHEDVLF+70/DQGLQYRNLQJDdata-
roleW\SHFDOOHGOLVWYLHZ

Discussion
7KLV H[DPSOH GRHVQ¦W FRQWDLQ DQ\ 3KRQH*DS ZRUN KRZHYHU LI \RX DUH EXLOGLQJ D
PRELOHDSSOLFDWLRQZLWK3KRQH*DSDQG\RXKDYHDQ\GDWDWKDW\RXZLVKWRGLVSOD\LQ
DKLHUDUFK\\RXZLOOPRVWFHUWDLQO\ZDQWWRGLVSOD\LWXVLQJWKHVWDQGDUGWDEOHOLVWLQJ
WKDWDOORZVWKHXVHUWRVFUROOXSDQGGRZQZLWKDILQJHU
7RVWDUWFUHDWHDQHZILOHFDOOHGOLVWKWPO$OLQNLQWKHH[LVWLQJ+70/SDJHVVKRXOGEH
DGGHGWRWKLVRQH7KHIROORZLQJ+70/LQWKHILOHZLOOLPSOHPHQWWKHOLVW
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="list-page">
<div data-role="header" data-position="inline">
<h1>Types of animals</h1>
</div>

<ul data-role="listview">
<li>Farm
<ul>
<li><a href="#">Cows</a></li>
<li><a href="#">Chickens</a></li>
<li><a href="#">Pigs</a></li>
</ul>
</li>
<li>Wild
<ul>
<li><a href="#">Giraffes</a></li>
<li><a href="#">Lions</a></li>

28 | The Recipes

www.it-ebooks.info
<li><a href="#">Tigers</a></li>
</ul>
</li>
<li>Pets
<ul>
<li><a href="#">Cats</a></li>
<li><a href="#">Dogs</a></li>
<li><a href="#">Gerbals</a></li>
</ul>
</li>
</ul>

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="map.html">Map</a></li>
<li><a href="compass.html">Compass</a></li>
<li><a href="list.html"
class="ui-btn-active">List</a></li>
</ul>
</div>
</div>
</div>
</body>
</html>

7KHNH\IDFWRUWKDWLPSOHPHQWVWKHOLVWLVdata-role="listview"RQWKHILUVWulWDJ)URP
WKHUHDQHVWHGXQRUGHUHGOLVWLVFUHDWHG2QHDFKLQQHUOLVWDOLQNLVDGGHGWRWKHHOHPHQW
WKDWVKRXOGJRWRWKHGHWDLOSDJH7KHdata-role="listview"FRQWDLQVDORWRIRSWLRQV
IRUFXVWRPL]LQJWKHORRNDQGIHHO)RUH[DPSOHDEXEEOHFRXQWFDQDSSHDUEHVLGHWKH
HOHPHQWGLYLGHUVFDQEHDGGHGWRVHSDUDWHDJURXSRIGDWD WKLVZLOOEHXVHGLQDIXWXUH
UHFLSH ZKHQ UHWULHYLQJ D OLVW RI FRQWDFWV  DQG PXFK PRUH 7KHUH LV QR OLPLW WR WKH
QXPEHURIQHVWHGulWDJVLQFDVHWZROHYHOVGHHSLVQRWVXIILFLHQW

Retrieving Contacts in the Address Book


Problem
<RXZDQWWRUHWULHYHDQGGLVSOD\WKHOLVWRIFRQWDFWVWKDWWKHXVHUKDVVDYHGRQWKHGHYLFH

Solution
7KH3KRQH*DS$3,H[SRVHVDIXQFWLRQFDOOHGcontacts.findWKDWDFFHSWVIRXUSDUDP
HWHUVLQFOXGLQJWKHDELOLW\WRVHDUFKIRUDVSHFLILFFRQWDFW%\XVLQJWKLVIXQFWLRQLQ
FRQMXQFWLRQZLWKWKHM4XHU\PRELOHOLEUDU\\RXFDQGLVSOD\DOLVWRIFRQWDFWVLQDWDEOH
YLHZWKDWRQFHDFRQWDFWLVVHOHFWHGZLOOGLVSOD\WKHFRQWDFW¦VIXOOLQIRUPDWLRQ

Retrieving Contacts in the Address Book | 29

www.it-ebooks.info
Discussion
6HYHUDOQHZILOHVPXVWEHFUHDWHGWRDFFRPSOLVKWKLV7REHJLQ\RXPXVWFUHDWHWKH
PDLQFRQWDFWOLVWLQJSDJH,QVLGHRI\RXUDVVHWVZZZGLUHFWRU\FUHDWHDQHZILOHFDOOHG
FRQWDFWVKWPO7KLVILOHZLOOVLPSO\KROGWKHVNHOHWRQ+70/WKDWZLOOEHSRSXODWHGYLD
-DYD6FULSW
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="contacts-page">
<div data-role="header" data-position="inline">
<h1>Contacts</h1>
</div>

<ul id="contactList" data-role="listview">

</ul>

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="map.html">Map</a></li>
<li><a href="compass.html">Compass</a></li>
<li><a href="list.html">List</a></li>
<li><a href="contacts.html"
class="ui-btn-active">Contacts</a></li>
</ul>
</div>
</div>

<script type="text/javascript" charset="utf-8"


src="scripts/contacts.js"></script>
</div>
</body>
</html>

6RPHNH\GHVLJQHOHPHQWVKDYHEHHQDGGHGLQWKHSUHFHGLQJ+70/)LUVWO\DQHZ
data-role="header"KDVEHHQDGGHGMXVWLQVLGHWKHSDJHUROH7KLVZLOOGLVSOD\DKHDGHU
EDUZLWKWKHWLWOHRI&RQWDFWV7KHQDQHPSW\ulWDJKDVEHHQDGGHGZLWKWKHSUHYLRXVO\
XVHGdata-role="listview"DWWULEXWHZKLFKZLOOEHSRSXODWHGQH[WZLWKWKHFRQWDFWV
%HVXUHWRJREDFNWR\RXUH[LVWLQJ+70/ILOHVDQGDGGWKHOLQNWRWKHQHZFRQWDFWV
SDJH
7KHQDQRWKHU+70/SDJHQHHGVWREHFUHDWHGWKDWZLOOGLVSOD\WKHIXOOFRQWDFWLQIRU
PDWLRQZKHQFOLFNHGRQ,QVLGHRI\RXUDVVHWVZZZGLUHFWRU\FUHDWHDQHZILOHFDOOHG
YLHZKWPO

30 | The Recipes

www.it-ebooks.info
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="contactview-page">
<div data-role="header" data-position="inline">
<h1>View Contact</h1>
</div>

<div id="contact">

</div>

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="map.html">Map</a></li>
<li><a href="compass.html">Compass</a></li>
<li><a href="list.html">List</a></li>
<li><a href="contacts.html"
class="ui-btn-active">Contacts</a></li>
</ul>
</div>
</div>

<script type="text/javascript" charset="utf-8"


src="scripts/contacts.js"></script>
</div>
</body>
</html>

$QRWKHUKHDGHUHOHPHQWKDVEHHQDGGHGKHUHZLWKWKHWLWOHRI9LHZ&RQWDFWDQGDQ
HPSW\divWDJKDVEHHQDGGHGZLWKWKH,'RIFRQWDFW7KLVZLOOEHXVHGWRSRSXODWHWKH
FRQWDFWLQIRUPDWLRQLQVLGHRIWKDWSDJH
1RZWKH-DYD6FULSWPXVWEHFUHDWHG%HJLQE\FUHDWLQJDQHZFRQWDFWVMVILOHLQVLGHRI
\RXUDVVHWVZZZVFULSWVGLUHFWRU\
function onContactsLoad() {
var fields = ["id", "displayName", "name"];
navigator.contacts.find(fields, showContacts);
}

function onViewLoad() {
// get the contact by the displayName from the URL
var fields = ["id", "displayName", "name",
"emails", "phoneNumbers"];
var options = new ContactFindOptions();
options.filter = getParameterByName("id");
navigator.contacts.find(fields, showContact,
onError, options);
}

Retrieving Contacts in the Address Book | 31

www.it-ebooks.info
function showContact(contacts) {
if (contacts.length > 0) {
var contact = contacts[0];

$("#contact").append("<h2>" +
contact.name.givenName + " " +
contact.name.familyName + "</h2>");
if (contact.emails.length > 0) {
$("#contact").append("<h3>Emails</h3>");
$("#contact").append("<ul>");
}
for (var i = 0; i < contact.emails.length; i++) {
$("#contact").append("<li>" +
contact.emails[i].value + "</li>");
}
if (contact.emails.length > 0) {
$("#contact").append("</ul>");
}
if (contact.phoneNumbers.length > 0) {
$("#contact").append("<h3>Phone Numbers</h3>");
$("#contact").append("<ul>");
}
for (var i = 0; i < contact.phoneNumbers.length; i++) {
$("#contact").append("<li>" +
contact.phoneNumbers[i].value + "</li>");
}
if (contact.phoneNumbers.length > 0) {
$("#contact").append("</ul>");
}

} else {
alert("Unable to find contact");
}
}

function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace
(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(currentUrl);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace
(/\+/g, " "));
}

function showContacts(contacts) {
var cSort = function(a, b) {
aName = a.name.givenName;
bName = b.name.givenName;
return aName < bName ? -1 : (aName == bName ? 0 : 1);
};

32 | The Recipes

www.it-ebooks.info
contacts = contacts.sort(cSort);

var dividers = "";


for (var i = 0; i < contacts.length; i++) {
var firstLetter = contacts[i].name.givenName.
charAt(0).toUpperCase();
// check if we need to add a divider
if (dividers.indexOf(firstLetter) < 0) {
dividers += firstLetter;
$("#contactList").append(
"<li data-role=\"list-divider\">" + firstLetter + "</li>");
}
$("#contactList").append(
"<li><a href=\"view.html?id=" + contacts[i].id +
"\">" + contacts[i].name.givenName + " " +
contacts[i].name.familyName + "</a></li>");
}

$("#contactList").listview('refresh');
}

function onError(contactError) {
alert("Error = " + contactError.code);
return false;
}

4XLWH D ELW LV KDSSHQLQJ LQ WKLV -DYD6FULSW ILOH 7KH ILUVW WZR IXQFWLRQV onContacts
LoadDQGonViewLoadSHUIRUPDVHDUFKIRUWKHFRQWDFWV7KHILUVWIXQFWLRQUHWULHYHVDOO
FRQWDFWVLQWKHDGGUHVVERRN7KHVHFRQGIXQFWLRQILOWHUVWKHFRQWDFWVE\WKHLGWKDWLV
SDVVHGLQYLDWKH85/WRUHWULHYHDVLQJOHFRQWDFW HJWRGLVSOD\WKHIXOOLQIRUPDWLRQ
DERXWWKHFRQWDFWVHOHFWHGIURPWKHOLVW 
7KHQH[WIXQFWLRQshowContactUHFHLYHVWKHOLVWRIFRQWDFWVIURPWKHVXFFHVVIXOFRQWDFW
UHWULHYDORIonViewLoad7KLVIXQFWLRQWKHQGLVSOD\VVRPHEDVLFLQIRUPDWLRQDERXWWKH
FRQWDFW7KHUHDUHPRUHILHOGVWKDWFDQEHDGGHGEXWFXUUHQWO\LWZLOOMXVWGLVSOD\WKH
QDPHHPDLODGGUHVVHVDQGSKRQHQXPEHUVIRUWKHFRQWDFW7KHIXOOOLVWRIFRQWDFWILHOGV
FDQEHIRXQGDWWKH3KRQH*DSSDJHDERXWFRQWDFWV

%H VXUH WR UHDG WKH TXLUNV DERXW HDFK ILHOG FDUHIXOO\ DV WKH VXSSRUW
EHWZHHQHDFKGHYLFHYDULHVJUHDWO\LQVRPHLQVWDQFHV

7KHgetParameterByNameIXQFWLRQLVDVLPSOHKHOSHUIXQFWLRQWKDWLVXVHGWRUHWULHYHWKH
LGIURPWKHTXHU\VWULQJ
7KHILQDOIXQFWLRQshowContactsLVFDOOHGZKHQDVXFFHVVIXOOLVWRIFRQWDFWVLVUHFHLYHG
IURPWKHILUVWIXQFWLRQonContactsLoadshowContactsUHFHLYHVDOLVWRIFRQWDFWVLWHUDWHV
WKURXJK HDFK RQH DQG DSSHQGV D QHZ OLVW LWHP WR WKH WDEOH YLHZ FUHDWHG LQ WKH
FRQWDFWVKWPO ILOH $V D QLFH DGGLWLRQ WKH FRQWDFWV DUH VRUWHG DOSKDEHWLFDOO\ E\ WKH

Retrieving Contacts in the Address Book | 33

www.it-ebooks.info
JLYHQ1DPH7KLVLVGRQHVRWKDWGLYLGHUVFDQEHDGGHGWRJURXSWKHLWHPVE\WKHILUVW
OHWWHURIWKHFRQWDFW¦VQDPH

See Also
£'LVSOD\LQJ7DEOH9LHZ'DWD¤RQSDJH

Creating a New Contact in the Address Book


Problem
<RXZDQWWRDOORZ\RXUDSSOLFDWLRQWRFUHDWHDQGVDYHDQHZFRQWDFWRUHGLWDQH[LVWLQJ
FRQWDFWLQWKHGHYLFH¦VDGGUHVVERRN

Solution
7KH3KRQH*DS$3,H[SRVHVDIXQFWLRQFDOOHGcontacts.createWKDWDFFHSWVDVWUXFWXUH
ZLWKWKHLQIRUPDWLRQDERXWWKHFRQWDFW,WFUHDWHVDQHZContactREMHFWWKDWFRQWDLQVD
saveIXQFWLRQWRDGGWKHFRQWDFWWRWKHDGGUHVVERRN:KHQWKH Contact.idDOUHDG\
H[LVWVWKHLQIRUPDWLRQLVXSGDWHGLQVWHDGRIFUHDWLQJDQHZFRQWDFW%\FUHDWLQJDQHZ
IRUPWKDWDOORZVWKHXVHUWRHQWHULQIRUPDWLRQDERXWWKHFRQWDFWZKHQWKHXVHUVXEPLWV
WKHGDWDLWZLOOEHVDYHGLQWKHDGGUHVVERRN

Discussion
7KHILUVWWKLQJWKDW\RXQHHGWRGRLVFUHDWHDQHZIRUP,QVLGHRI\RXUDVVHWVZZZ
GLUHFWRU\FUHDWHDQHZILOHFDOOHGIRUPKWPO7KLVFRQWDLQVDEDVLFIRUPWKDWZLOOEHXVHG
WRFROOHFWWKHFRQWDFW¦VLQIRUPDWLRQ
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="form-page">
<div data-role="header" data-position="inline">
<a href="contacts.html" data-icon="delete">
Cancel</a>
<h1>Add Contact</h1>
<a onClick="return saveContact()" href="#"
data-icon="check" data-theme="b">Save</a>
</div>

<form action="form.html" method="post">


<input type="hidden" name="id" value="0" />
<table>

34 | The Recipes

www.it-ebooks.info
<tr>
<td>Display Name</td>
<td><input type="text" name="displayName"
value="" /></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name="firstName"
value="" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName"
value="" /></td>
</tr>
<tr>
<td>Email (Home)</td>
<td><input type="text" name="email_home"
value="" /></td>
</tr>
<tr>
<td>Email (Work)</td>
<td><input type="text" name="email_work"
value="" /></td>
</tr>
<tr>
<td>Email (Other)</td>
<td><input type="text" name="email_other"
value="" /></td>
</tr>
<tr>
<td>Phone (Home)</td>
<td><input type="text" name="phone_home"
value="" /></td>
</tr>
<tr>
<td>Phone (Work)</td>
<td><input type="text" name="phone_work"
value="" /></td>
</tr>
<tr>
<td>Phone (Other)</td>
<td><input type="text" name="phone_other"
value="" /></td>
</tr>
</table>
</form>

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="map.html">Map</a></li>
<li><a href="compass.html">Compass</a></li>
<li><a href="list.html">List</a></li>

Creating a New Contact in the Address Book | 35

www.it-ebooks.info
<li><a href="contacts.html"
class="ui-btn-active">Contacts</a></li>
</ul>
</div>
</div>

<script type="text/javascript" charset="utf-8"


src="scripts/contacts.js"></script>
</div>
</body>
</html>

$6DYHDQG&DQFHOEXWWRQKDYHEHHQDGGHGWRWKHKHDGHUEDUDQGWKHYDULRXVFRQWDFW
ILHOGVWKDWDUHVKRZQLQWKHYLHZSDJHDUHLQFOXGHGLQWKLVIRUP
7ZRPLQRUXSGDWHVQHHGWREHPDGHWRWKHFRQWDFWVKWPODQGYLHZKWPOSDJHV7KH
KHDGHUEDUQHHGVWREHXSGDWHGWRLQFOXGH$GGDQG(GLWEXWWRQVLQWKHUHVSHFWLYHSDJHV
WKDWZLOOOLQNWKHXVHUWRWKHIRUP%HORZLVWKHXSGDWHGKHDGHUIRUWKHFRQWDFWVKWPOILOH
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="contacts-page">
<div data-role="header" data-position="inline">
<h1>Contacts</h1>
<a href="form.html" data-icon="save"
data-theme="b">Add</a>
</div>

...

$QGQRZWKHYLHZKWPOILOH
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="contactview-page">
<div data-role="header" data-position="inline">
<h1>View Contact</h1>
<a href="form.html" data-icon="save"
data-theme="b">Edit</a>
</div>

...

)LQDOO\WKHFRQWDFWVMVILOHUHTXLUHVVHYHUDOFKDQJHVDQGPDQ\QHZDGGLWLRQVWRKDQGOH
WKHDGGLQJDQGHGLWLQJRIWKHFRQWDFW7KHFRPSOHWHFRQWDFWVMVILOHIROORZVZLWKWKH
FRGHIRUUHWULHYLQJWKHFRQWDFWVDVZHOO

36 | The Recipes

www.it-ebooks.info
function onContactsLoad() {
var fields = ["id", "displayName", "name"];
navigator.contacts.find(fields, showContacts);
}

function onViewLoad() {
getContactById(getParameterByName("id"), showContact);
}

function onFormLoad() {
var id = getParameterByName("id");

// if there is an id, load the contact


if (id.length > 0) {
getContactById(id, populateForm);
}
}

function getContactById(id, callback) {


// get the contact by the displayName from the URL
var fields = ["id", "displayName", "name",
"emails", "phoneNumbers"];
var options = new ContactFindOptions();
options.filter = id;
navigator.contacts.find(fields, callback,
onError, options);
}

function showContact(contacts) {
if (contacts.length > 0) {
var contact = contacts[0];

// update the link to include the id


$("a[href='form.html']").attr("href", function(i, href) {
return href + "?id=" + contact.id;
});

$("#contact").append("<h2>" +
contact.name.givenName + " " +
contact.name.familyName + "</h2>");
if (contact.emails.length > 0) {
$("#contact").append("<h3>Emails</h3>");
$("#contact").append("<ul>");
}
for (var i = 0; i < contact.emails.length; i++) {
$("#contact").append("<li>" +
contact.emails[i].value + "</li>");
}
if (contact.emails.length > 0) {
$("#contact").append("</ul>");
}
if (contact.phoneNumbers.length > 0) {
$("#contact").append("<h3>Phone Numbers</h3>");
$("#contact").append("<ul>");
}

Creating a New Contact in the Address Book | 37

www.it-ebooks.info
for (var i = 0; i < contact.phoneNumbers.length; i++) {
$("#contact").append("<li>" +
contact.phoneNumbers[i].value + "</li>");
}
if (contact.phoneNumbers.length > 0) {
$("#contact").append("</ul>");
}
} else {
alert("Unable to find contact");
}
}

function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace
(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(currentUrl);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace
(/\+/g, " "));
}

function showContacts(contacts) {
var cSort = function(a, b) {
var aName = a.name.givenName;
var bName = b.name.givenName;
return aName < bName ? -1 :
(aName == bName ? 0 : 1);
};
contacts = contacts.sort(cSort);

var dividers = "";


for (var i = 0; i < contacts.length; i++) {
var firstLetter = contacts[i].name.givenName.charAt(0).toUpperCase();
// check if we need to add a divider
if (dividers.indexOf(firstLetter) < 0) {
dividers += firstLetter;
$("#contactList").append("<li data-role=\"list-divider\">" + firstLetter
+ "</li>");
}
$("#contactList").append("<li><a href=\"view.html?id=" + contacts[i].id + "\">"
+ contacts[i].name.givenName + " " + contacts[i].name.familyName + "</a></li>");
}

$("#contactList").listview('refresh');
}

function populateForm(contacts) {
if (contacts.length > 0) {
var contact = contacts[0];
var form = document.getElementsByTagName('form')[0].elements;

38 | The Recipes

www.it-ebooks.info
form.id.value = contact.id;
form.displayName.value = contact.displayName;
form.firstName.value = contact.name.givenName;
form.lastName.value = contact.name.familyName;
if (contact.emails.length > 0) {
form.email_home.value = contact.emails[0].value;
if (contact.emails.length > 1) {
form.email_work.value = contact.emails[1].value;
if (contact.emails.length > 2) {
form.email_other.value = contact.emails[2].value;
}
}
}
if (contact.phoneNumbers.length > 0) {
form.phone_home.value = contact.phoneNumbers[0].value;
if (contact.phoneNumbers.length > 1) {
form.phone_work.value = contact.phoneNumbers[1].value;
if (contact.phoneNumbers.length > 2) {
form.phone_other.value = contact.phoneNumbers[2].value;
}
}
}
}
}

function saveContact(contacts) {
var form = document.getElementsByTagName('form')[0].elements;
var contact;

if (form.id.value != 0 && typeof contacts == "undefined") {


getContactById(form.id.value, saveContact);
} else if (typeof contacts != "undefined") {
contact = contacts[0];
} else {
contact = navigator.contacts.create();
}

contact.displayName = form.displayName.value;
contact.nickname = form.displayName.value;

var name = new ContactName();


name.givenName = form.firstName.value;
name.familyName = form.lastName.value;
contact.name = name;

var emails = new Array();


if (form.email_home.value.length > 0) {
emails[emails.length] = new ContactField('home', form.email_home.value);
}
if (form.email_work.value.length > 0) {
emails[emails.length] = new ContactField('work', form.email_work.value);
}
if (form.email_other.value.length > 0) {
emails[emails.length] = new ContactField('other', form.email_other.value);
}

Creating a New Contact in the Address Book | 39

www.it-ebooks.info
contact.emails = emails;

var phoneNumbers = new Array();


if (form.phone_home.value.length > 0) {
phoneNumbers[phoneNumbers.length] = new ContactField('home',
form.phone_home.value);
}
if (form.phone_work.value.length > 0) {
phoneNumbers[phoneNumbers.length] = new ContactField('work',
form.phone_work.value);
}
if (form.phone_other.value.length > 0) {
phoneNumbers[phoneNumbers.length] = new ContactField('other',
form.phone_other.value);
}
contact.phoneNumbers = phoneNumbers;

contact.save(onSuccess,onError);
}

function onSuccess(contact) {
alert("Save Success");
$.mobile.changePage("contacts.html");
}

function onError(contactError) {
alert("Error = " + contactError.code);
}

7KHH[LVWLQJonViewLoadIXQFWLRQKDVEHHQFKDQJHGWRFDOODQHZgetContactByIdIXQF
WLRQEHFDXVHWKHVDPHIXQFWLRQDOLW\LVDOVRXVHGLQVLGHRIWKHQHZonFormLoadIXQFWLRQ
WKDWSRSXODWHVWKHHGLWIRUPZLWKFRQWDFWLQIRUPDWLRQZKHQWKHXVHUVHOHFWV(GLW
:KHQWKHFRQWDFWVKDYHEHHQVXFFHVVIXOO\UHWULHYHGWKHshowContactIXQFWLRQLVFDOOHG
RQWKHYLHZSDJH7KLVIXQFWLRQKDVEHHQDOWHUHGWRDSSHQGWKHFRQWDFW¦V,'WRWKH(GLW
OLQN85/VRWKHFRQWDFWFDQEHUHWULHYHGRQWKHIRUPSDJH
)LQDOO\IRXUQHZIXQFWLRQVKDYHEHHQDGGHGWRSRSXODWHDQGVDYHWKHFRQWDFW)LUVW
WKHpopulateFormIXQFWLRQLVFDOOHGDIWHUWKHXVHUFOLFNV(GLWDQGWKHFRQWDFWKDVEHHQ
UHWULHYHG,WVLPSO\H[WUDFWVWKHGDWDIURPWKH ContactREMHFWDQGSRSXODWHVWKHIRUP
YDOXHV:KHQWKHXVHUSUHVVHVWKH6DYHEXWWRQWKHsaveContactIXQFWLRQLVFDOOHG7KLV
ZRUNVVLPLODUWRSRSXODWLQJWKHIRUPEXWLQUHYHUVH7KHYDOXHVDUHH[WUDFWHGIURPWKH
IRUPDQGVDYHGLQWKHFRQWDFW
$IHZLPSRUWDQWWKLQJVDUHKDSSHQLQJLQVLGHWKLVIXQFWLRQ,IWKHXVHULVHGLWLQJWKH
XVHUWKHFRQWDFWPXVWEHUHWULHYHGDQGXSGDWHGRWKHUZLVHDQHZFRQWDFWLVFUHDWHG
WKURXJK WKH navigator.contacts.create() IXQFWLRQ 7KH QDPH HPDLOV DQG SKRQH
QXPEHUVDUHVSHFLDOILHOGVEHFDXVHWKH\DUHFUHDWHGWKURXJKRWKHU3KRQH*DS Contact
REMHFWV7KHQDPHPXVWEHGHILQHGDVDQHZContactNameREMHFWDQGERWKWKHHPDLODQG
SKRQHQXPEHUVPXVWEHGHILQHGDVQHZContactFieldsLQVLGHDQDUUD\EHFDXVHPXOWLSOH
W\SHVFDQEHDGGHG

40 | The Recipes

www.it-ebooks.info
7KHUHDUHVHYHUDOPRUHFRQWDFWILHOGVWKDW\RXFDQDGG6HHWKH3KRQH*DSGRFXPHQ
WDWLRQIRUPRUHLQIRUPDWLRQEHFDXVHQRWDOOGHYLFHVVXSSRUWDOORIWKHILHOGV
7KHODVWWZRIXQFWLRQVKDQGOHDVXFFHVVIXOVDYHDQGHUURUVWKDWPLJKWRFFXUZKLOHVDYLQJ
WKHFRQWDFW8SRQVXFFHVVWKHXVHULVUHGLUHFWHGEDFNWRWKHFRQWDFWVKWPOSDJHXVLQJ
WKH$.mobile.changePageIXQFWLRQ

,W¦VLPSRUWDQWWRQRWHWKDWWKH$.mobile.changePageZDVXVHGDQGQRWD
VWDQGDUG-DYD6FULSWUHGLUHFWZLWKlocation.href,IWKHODWWHUZHUHSHU
IRUPHGWKHM4XHU\PRELOHOLEUDU\ZRXOGEHORVWEHFDXVHQR$-$;UH
TXHVW LV SHUIRUPHG DQG WKHUH ZRXOG EH D IUHVK ORDG RI WKH
FRQWDFWVKWPOILOHZLWKRXWWKHQHFHVVDU\-DYD6FULSWILOHV ZKLFKDUHRQO\
LQFOXGHGLQWKHLQGH[KWPOILOH 

See Also
$GGLQJ%XWWRQVWR+HDGHU%DUV

Accessing the Camera and Photo Album


Problem
<RXZDQWWRDOORZ\RXUDSSOLFDWLRQWRWDNHSLFWXUHVZLWKWKHFDPHUDRUVHOHFWRQHRI
WKHXVHU¦VH[LVWLQJSKRWRV

Solution
7KH3KRQH*DS$3,H[SRVHVDIXQFWLRQFDOOHGcamera.getPictureWKDWDFFHVVHVWKHGH
YLFH¦VGHIDXOWSKRWRDSSOLFDWLRQDOORZLQJWKHXVHUWRYLHZDQGVHOHFWSKRWRVRUWDNHD
QHZSKRWRZLWKWKHFDPHUD

Discussion
7REHJLQWKLVH[DPSOHDQHZ+70/ILOHLVUHTXLUHGWRGLVSOD\DVHOHFWHGSKRWRIURP
WKHOLEUDU\RUDQHZSLFWXUHIURPWKHFDPHUD&UHDWHDQHZILOHFDOOHGSKRWRVKWPOLQVLGH
RI\RXUDVVHWVZZZGLUHFWRU\%HVXUHWRDGGDQHZOLQNWRWKLVILOHLQ\RXUH[LVWLQJILOHV
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="contacts-page">
<div data-role="header" data-position="inline">
<h1>Photos</h1>

Accessing the Camera and Photo Album | 41

www.it-ebooks.info
</div>

<img src="" id="photo" />

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="map.html">Map</a></li>
<li><a href="compass.html">Compass</a></li>
<li><a href="list.html">List</a></li>
<li><a href="contacts.html">Contacts</a></li>
<li><a href="photos.html"
class="ui-btn-active">Photos</a></li>
</ul>
</div>
</div>

<script type="text/javascript" charset="utf-8"


src="scripts/photos.js"></script>
</div>
</body>
</html>

2QFHDJDLQWKHUH¦VQRWKLQJWRRVSHFLDOLQWKH+70/ILOHDSDUWIURPLQFOXGLQJDQHZ
-DYD6FULSWILOHFDOOHGSKRWRVMVDQGDQHPSW\imgWDJZLWKWKH,'RISKRWR7KLVZLOOEH
XVHGGLVSOD\WKHSKRWRDIWHUZDUGV
<RXQRZQHHGWRFUHDWHWKHSKRWRVMVILOHLQVLGHRI\RXUDVVHWVZZZVFULSWVIROGHU
var loaded = false;

function onPhotosLoad() {
// only load the camera selector on first load
if (!loaded) {
navigator.camera.getPicture(onPhotoLoadSuccess, onFail,
{
quality: 50,
encodingType: Camera.EncodingType.PNG,
destinationType: navigator.camera.DestinationType.FILE_URI
});

loaded = true;
}
}

function onPhotoLoadSuccess(photoUri) {
document.getElementById('photo').src = photoUri;
}

function onFail(message) {
alert('Failed because: ' + message);
}

42 | The Recipes

www.it-ebooks.info
,QVLGHWKHonPhotosLoadFDOOEDFNIXQFWLRQWKHnavigator.camera.getPictureLVXVHGWR
DFFHVVWKHFDPHUD,WDFFHSWVWKUHHSDUDPHWHUVWKHFDOOEDFNWRLQYRNHXSRQVXFFHVV
WKHFDOOEDFNWRLQYRNHXSRQIDLOXUHDQGRSWLRQVLQVWUXFWXUHGIRUPDW,QWKHDERYH
H[DPSOH WKH destinationType RSWLRQ LV GHILQHG DV navigator.camera.Destination
Type.FILE_URIZKLFKZLOOUHWXUQWKHSKRWRDVDILOHSDWK7KLVSDWKLVWKHQXVHGLQVLGH
RIonPhotoLoadSuccessWRVHWWKHVRXUFHRIWKHSUHYLRXVO\FUHDWHGLPDJH
,IWKH destinationTypeRSWLRQLVRPLWWHGWKHGHIDXOWW\SHXVHGLVDEDVHHQFRGHG
LPDJH
,I\RXZDQWWRDOORZWKHXVHUWRDFFHVVWKHSKRWROLEUDU\LQVWHDGRIWDNLQJDSLFWXUHWKH
SUHFHGLQJH[DPSOHZRXOGQHHGWREHHGLWHGWRVSHFLI\DsourceTypeRSWLRQDVZHOO
navigator.camera.getPicture(onPhotoLoadSuccess, onFail,
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
});

Saving Data to a Remote Server


Problem
<RXZDQWWRXSORDGDILOHIURPWKHORFDOGHYLFHWRDQH[WHUQDOVHUYHU

Solution
$IWHUWKHXVHUKDVVHOHFWHGDORFDOPHGLDLWHPWKHFileTransferFODVVLVXVHGWRSHUIRUP
DQ+7733267FRQWDLQLQJWKHE\WHGDWDWRDQH[WHUQDOVHUYHU7KHH[WHUQDOVHUYHU
PXVWH[SRVHDZHEVHUYLFHWKDWDFFHSWVDQGSHUIRUPVWKHUHPRWHVDYLQJ 7KLVLVRXWVLGH
WKHVFRSHRIWKLVERRNKRZHYHUPDQ\3+3$631(7HWFVFULSWVFDQEHIRXQGRQ
WKH,QWHUQHWWRKHOS

Discussion
7KLVH[DPSOHZLOOH[WHQGWKHSUHYLRXVUHFLSHDQGVDYHWKHSKRWRWKDWZDVWDNHQRU
VHOHFWHG7RVWDUWWKHSUHYLRXVO\FUHDWHGSKRWRVKWPOSDJHQHHGVWREHXSGDWHGWRLQ
FOXGHDEXWWRQWRVDYHWKHILOH7KLVFDQEHDGGHGLQWKHKHDGHUDVIROORZV
<div data-role="header" data-position="inline">
<h1>Photos</h1>
<a onClick="return savePhoto()" href="#"
data-icon="check" data-theme="b">Save</a>
</div>

:KHQWKHXVHUFOLFNVWKH6DYHEXWWRQDQHZsavePhotoIXQFWLRQLVFDOOHGWKDWZLOOXVH
WKH FileTransferFODVVWRXSORDGWKHSKRWRWRDUHPRWHVHUYHU7KLVQHZIXQFWLRQDV

Saving Data to a Remote Server | 43

www.it-ebooks.info
ZHOODVWZRRWKHUVWRGHDOZLWKDVXFFHVVRUIDLOUHVSRQVHIURPWKHVHUYHUVKRXOGEH
DGGHGWRWKHH[LVWLQJSKRWRVMVILOHFUHDWHGLQ£$FFHVVLQJWKH&DPHUDDQG3KRWR$O
EXP¤RQSDJH
var loaded = false;
var currentPhoto = null;

function onPhotosLoad() {
// only load the camera selector on first load
if (!loaded) {
navigator.camera.getPicture(onPhotoLoadSuccess, onFail,
{
quality: 50,
encodingType: Camera.EncodingType.PNG,
destinationType:
navigator.camera.DestinationType.FILE_URI
});

loaded = true;
}
}

function onPhotoLoadSuccess(photoUri) {
// store current photo for saving later
currentPhoto = photoUri;

document.getElementById('photo').src = photoUri;
}

function onFail(message) {
alert('Failed because: ' + message);
}

function savePhoto() {
if (currentPhoto == null) {
alert("Please select a photo first");
return;
}

var uploadOptions = new FileUploadOptions();


uploadOptions.fileKey = "file";
uploadOptions.fileName =
currentPhoto.substr(currentPhoto.lastIndexOf('/') + 1);
uploadOptions.mimeType="image/png";

var fileTransfer = new FileTransfer();


// Be sure to update the URL below to your site
fileTransfer.upload(currentPhoto,
"http://www.webistrate.com/phonegap/upload.php",
uploadSuccess, uploadFail, uploadOptions);
}

function uploadSuccess(result) {
alert("Successfully transferred " +
result.bytesSent + "bytes");

44 | The Recipes

www.it-ebooks.info
}

function uploadFail(error) {
alert("Error uploading file: " + error.code);
}

7KHH[DPSOHLQFOXGHVDQHZJOREDOYDULDEOHcurrentPhoto7KLVYDULDEOHLVVHWDIWHUWKH
XVHU VHOHFWV RU WDNHV D SLFWXUH 7KH YDULDEOH LV WKHQ FKHFNHG DW WKH WRS RI WKH save
PhotoIXQFWLRQWRHQVXUHWKDWWKHXVHUVHOHFWHGDSKRWREHIRUHXSORDGLQJ
1H[WVHYHUDOYDULDEOHVDUHFUHDWHG7KHILUVW FileUploadOptionsFRQWDLQVWKHLQIRU
PDWLRQDERXWWKHSLFWXUH7KHVHFRQGYDULDEOHfileKeyFRQWDLQVWKHQDPHRIWKHYDUL
DEOHWKDWLVXVHGE\WKHVHUYHUVLGHVFULSWWRVDYHWKHSLFWXUH7KHILQDOWZRYDULDEOHV
fileNameDQGmimeTypeFRQWDLQWKHQDPHRIWKHILOHDQGWKHW\SHRIILOHUHVSHFWLYHO\
)LQDOO\DQHZFileTransferYDULDEOHLVGHILQHGVSHFLI\LQJWKHSKRWRWRXSORDGWKH85/
WRZKLFKDQ+7733267VKRXOGEHSHUIRUPHGWKHVXFFHVVDQGIDLOFDOOEDFNIXQFWLRQV
DQGWKHSUHYLRXVO\GHILQHGRSWLRQV
:KHQWKHXSORDGLVVXFFHVVIXOWKHH[DPSOHVLPSO\SUHVHQWVDVXFFHVVPHVVDJHDORQJ
ZLWKWKHQXPEHURIE\WHVWKDWZHUHVHQWWRWKHVHUYHU

Capturing Audio and Video


Problem
<RXZDQWWRDOORZWKHGHYLFHWRUHFRUGDXGLRRUYLGHRWKURXJK\RXUDSSOLFDWLRQ

Solution
7KH 3KRQH*DS $3, H[SRVHV WZR GLIIHUHQW IXQFWLRQV RQH IRU HDFK W\SH RI PHGLD WR
FDSWXUHcapture.captureAudioDQGcapture.captureVideo<RXFDQXVHWKHVHIXQFWLRQV
DORQJZLWKWKHFileTransferFODVVWRVDYHPHGLDDQGXSORDGLWWRDQH[WHUQDOVHUYHU

Discussion
7KHIROORZLQJH[DPSOHDOORZVWKHXVHUWRFUHDWHDQGXSORDGDQDXGLRRUYLGHRILOH7R
EHJLQDQHZ+70/ILOHPXVWEHFUHDWHG,QVLGHRI\RXUDVVHWVZZZGLUHFWRU\FUHDWHD
QHZILOHFDOOHGFDSWXUHKWPO%HVXUHWRDGGDOLQNWRWKLVQHZILOHLQ\RXUH[LVWLQJSDJHV
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="contacts-page">
<div data-role="header" data-position="inline">

Capturing Audio and Video | 45

www.it-ebooks.info
<h1>Capture</h1>
</div>

<input type="button" value="Capture Audio"


onclick="captureAudio()" />
<input type="button" value="Capture Video"
onclick="captureVideo()" />

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="map.html">Map</a></li>
<li><a href="compass.html">Compass</a></li>
<li><a href="list.html">List</a></li>
<li><a href="contacts.html">Contacts</a></li>
<li><a href="photos.html">Photos</a></li>
<li><a href="capture.html"
class="ui-btn-active">Capture</a></li>
</ul>
</div>
</div>

<script type="text/javascript" charset="utf-8"


src="scripts/capture.js"></script>
</div>
</body>
</html>

7KHIROORZLQJH[DPSOHFUHDWHVWZREXWWRQVRQHWKDWZLOODOORZWKHXVHUWRFDSWXUH
DXGLRDQGWKHRWKHUWRFDSWXUHYLGHR$QHZ-DYD6FULSWILOHFDSWXUHMVLVDOVRLQFOXGHG
7KLVILOHVKRXOGQRZEHFUHDWHGLQVLGHRI\RXUDVVHWVZZZVFULSWVGLUHFWRU\
7KLVILOHZLOOSURYLGHWZRFRUHIXQFWLRQVLQLWLDWHWKHFDSWXUHRIDXGLRDQGLQLWLDWHWKH
FDSWXUHRIYLGHR%HFDXVHWKHVHIXQFWLRQVZRUNLQWKHVDPHPDQQHURQO\RQHVXFFHVV
DQGRQHHUURUIXQFWLRQQHHGWREHFUHDWHG:KHQDVXFFHVVIXOPHGLDILOHLVUHFRUGHG
WKHILOHLVWKHQXSORDGHGWRDQH[WHUQDOZHEVLWHXVLQJWKHFileTransferFODVVLQDVLPLODU
PDQQHUWRWKHODVWUHFLSH
function captureAudio() {
navigator.device.capture.captureAudio(captureSuccess,
captureError);
}

function captureVideo() {
navigator.device.capture.captureVideo(captureSuccess,
captureError);
}

function captureSuccess(files) {
// more than 1 file might be returned
// so perform a loop and upload all of them
for (var i = 0; i < files.length; i++) {
uploadMediaFile(files[i]);

46 | The Recipes

www.it-ebooks.info
}
}

function captureError(error) {
alert("Error during capture = " + error.code);
}

function uploadMediaFile(file) {
var uploadOptions = new FileUploadOptions();
uploadOptions.fileKey = "file";
uploadOptions.fileName = currentPhoto.substr(
file.lastIndexOf('/') + 1);

var fileTransfer = new FileTransfer();


fileTransfer.path = file.fullPath;
fileTransfer.name = file.name;

fileTransfer.upload(file,
"http://www.webistrate.com/phonegap/upload.php",
uploadSuccess, uploadFail, uploadOptions);
}

function uploadSuccess(result) {
alert("Successfully transferred " +
result.bytesSent + "bytes");
}

function uploadFail(error) {
alert("Error uploading file: " + error.code);
}

-XVWDVLQWKHODVWH[DPSOHZKHQWKHPHGLDILOHXSORDGVVXFFHVVIXOO\WKH uploadSuc
cessIXQFWLRQLVFDOOHGWRLQIRUPWKHXVHUWKDWWKHXSORDGZDVFRPSOHWHG
2QHLPSRUWDQWWKLQJWRQRWHLQVLGHWKH captureSuccessIXQFWLRQD forORRSLVSHU
IRUPHGRQWKHfilesLQSXWSDUDPHWHU7KLVLVDQLPSRUWDQWIDFWRUEHFDXVHRQHRIWKH
RSWLRQVDYDLODEOHIRUERWKW\SHVRIFDSWXULQJLVWRDOORZWKHXVHUWRUHFRUGPRUHWKDQ
RQHILOHDWDWLPH7KLVLVGRQHE\VHWWLQJDOLPLWRSWLRQDVWKHWKLUGSDUDPHWHUIRUWKH
navigator.device.capture.captureVideoDQGWKHnavigator.device.capture.captureAu
dioIXQFWLRQV

See Also
£6DYLQJ'DWDWRD5HPRWH6HUYHU¤RQSDJH

Capturing Audio and Video | 47

www.it-ebooks.info
Notifying the Device with Alert, Confirm, and Vibrate
Problem
<RXZDQWWRFXVWRPL]HWKHVWDQGDUGDOHUWDQGFRQILUPGLDORJVRUQRWLI\WKHXVHUE\
PDNLQJWKHGHYLFHYLEUDWH

Solution
7KHVWDQGDUG-DYD6FULSWDOHUWDQGFRQILUPGLDORJVZRUNTXLWHZHOODQGDUHHYHQGLV
SOD\HGLQWKHGHYLFH¦VVW\OHKRZHYHULQ\RXUDSSOLFDWLRQ\RXPLJKWZDQWWRFXVWRPL]H
WKHEXWWRQVWKDWDSSHDURUHYHQPDNHWKHGHYLFHYLEUDWH OLNHDJDPHFRQWUROOHU 
7KH3KRQH*DS$3,H[SRVHVWKUHHGLIIHUHQWIXQFWLRQV notification.alert notifica
tion.confirmDQGnotification.vibrateZKLFKDUHXVHGWRQRWLI\WKHGHYLFH

Discussion
7RGHPRQVWUDWHWKH alertDQG confirmIXQFWLRQV,DPJRLQJWRRYHUULGHWKHGHIDXOW
-DYD6FULSWIXQFWLRQVWRDFFHSWWKHDGGLWLRQDOFXVWRPL]DWLRQSDUDPHWHUVWKDW3KRQH*DS
VXSSRUWV 7KLV ZLOO DOORZ \RX WR NHHS XVLQJ WKH VWDQGDUG -DYD6FULSW V\QWD[ \RX DUH
IDPLOLDUZLWKZKLOHSURYLGLQJDGGLWLRQDOFXVWRPL]DWLRQDVQHHGHG
7R EHJLQ FUHDWH D QHZ +70/ ILOH FDOOHG QRWLI\KWPO DQG VDYH LW LQ WKH DVVHWVZZZ
GLUHFWRU\7KLVILOHLVMXVWDSODFHKROGHUVRWKDWWKH-DYD6FULSWFDQEHH[SORUHGDQGWHVWHG
%HVXUHWRDGGDOLQNWRWKLVQHZILOHLQ\RXUH[LVWLQJSDJHV
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="contacts-page">
<div data-role="header" data-position="inline">
<h1>Notification Tests</h1>
</div>

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="map.html">Map</a></li>
<li><a href="compass.html">Compass</a></li>
<li><a href="list.html">List</a></li>
<li><a href="contacts.html">Contacts</a></li>
<li><a href="photos.html">Photos</a></li>
<li><a href="notify.html"
class="ui-btn-active">Notify</a></li>
</ul>

48 | The Recipes

www.it-ebooks.info
</div>
</div>

<script type="text/javascript" charset="utf-8"


src="scripts/notify.js"></script>
</div>
</body>
</html>

7KLVILOHVLPSO\ORDGVWKHQHZ-DYD6FULSWILOHQRWLI\MVZKLFKVKRXOGEHFUHDWHGLQVLGH
\RXUDVVHWVZZZVFULSWVGLUHFWRU\
function onNotifyLoad() {
alert("test 1");
alert("test 2", handleClick);
alert("test 3", handleClick, "My title");
alert("test 4", handleClick, "My title", "All done");

confirm("test 1");
confirm("test 2", handleConfirmClick);
confirm("test 3", handleConfirmClick, "My title");
confirm("test 4", handleConfirmClick, "My title",
"Play Again,Quit");

navigator.notification.vibrate(500);
navigator.notification.beep(3);
}

function handleClick() {

// button contains the name of the button clicked


// Windows Phone 7 ignores button names, always 'OK|Cancel'
function handleConfirmClick(button) {
if (button == 'Play Again' || button == 'OK') {
// do play again
} else if (button == 'Quit' || button == 'Cancel') {
// do quit code
}
}

// override the built in JavaScript alert function


function alert(msg, callback, title, button) {
navigator.notification.alert(msg, callback,
title, button);
}

function confirm(msg, callback, title, buttons) {


navigator.notification.confirm(msg, callback,
title, buttons);
}

,QWKHFDOOEDFNIXQFWLRQonNotifyLoadPXOWLSOHDOHUWVDQGFRQILUPDWLRQVDUHSHUIRUPHG
WRGHPRQVWUDWHKRZLWFDQVSHFLI\PRUHDQGPRUHGHWDLOGXULQJFDOOEDFN%RWKIXQFWLRQV

Notifying the Device with Alert, Confirm, and Vibrate | 49

www.it-ebooks.info
VXSSRUWDFDOOEDFNPHWKRGWKDWLVH[HFXWHGZKHQWKHXVHUFOLFNVRQHRIWKHEXWWRQV
IURPWKHGLDORJWKDWFDQSHUIRUPIXUWKHUSURFHVVLQJ)RUWKHFRQILUPFDOOEDFNIXQFWLRQ
WKHEXWWRQWH[WVKRZVXSDVWKHYDULDEOHWRFRQILUPZKLFKEXWWRQWKHXVHUSUHVVHG
,I\RXZDQWWRVHWDVGHIDXOWDQ\RIWKHYDULDEOHVSDVVHGWRWKHalertRUconfirmIXQFWLRQV
\RXFDQDOWHUWKHPDVIROORZV
// override the built in JavaScript alert function
function alert(msg, callback, title, button) {
if (typeof callback == 'undefined')
callback = handleClick;
if (typeof title == 'undefined')
title = "my title";
if (typeof button == 'undefined')
button = "click me";

navigator.notification.alert(msg, callback,
title, button);
}

7KLVLVDJUHDWZD\WRGHILQHDVWDQGDUGFXVWRPL]HGDOHUWRUFRQILUPGLDORJER[IRUDOO
RI\RXUH[LVWLQJDOHUWDQGFRQILUPWDJVZLWKPLQLPDOHIIRUW7KHVHIXQFWLRQVVKRXOG
WKHQEHPRYHGWR\RXUcommon.jsILOHVRWKH\FDQEHDFFHVVHGIURPDQ\SDJH
<RX PLJKW KDYH DOVR QRWLFHG WZR DGGLWLRQDO IXQFWLRQ FDOOV DW WKH ERWWRP RI WKH
onNotifyLoadIXQFWLRQV navigator.notification.vibrate(500)DQG navigator.notifi
cation.beep(3)
7KHYLEUDWHIXQFWLRQZLOOPDNHWKHGHYLFHYLEUDWHIRUWKHQXPEHURIPLOOLVHFRQGVGHILQHG
DVWKHILUVWSDUDPHWHU7KHEHHSIXQFWLRQZLOOPDNHWKHGHYLFHSOD\DVRXQGIRUWKH
QXPEHURIWLPHVVSHFLILHGDVWKHILUVWSDUDPHWHU

Storing Data to the Device


Problem
<RXZDQW\RXUDSSOLFDWLRQWRVDYHILOHVORFDOO\RQWKHSKRQH

Solution
7KH3KRQH*DS$3,SURYLGHVDFileWriterFODVVWKDWDOORZV\RXWRZULWHDQGVDYHDILOH
RQWKHGHYLFH7KHDirectoryEntryFODVVSURYLGHVDIXQFWLRQWRORDGWKHILOHWREHZULWWHQ

Discussion
7REHJLQWKLVH[DPSOHFUHDWHDQHZ+70/ILOHFDOOHGQRWHVKWPOLQVLGHRIWKHDVVHWV
ZZZ GLUHFWRU\ 7KLV ILOH VKRXOG VWDUW WR ORRN SUHWW\ VWDQGDUG ,W FRQWDLQV WKH EDVLF
+70/WRJHWWKHOD\RXWDQGQDYEDUDVZHOODVDIRUPWKDWFRQWDLQVDtextareaWRDOORZ

50 | The Recipes

www.it-ebooks.info
WKHXVHUWRHQWHUVRPHQRWHVWKDWZLOOEHVDYHGORFDOO\WRWKHGHYLFHXSRQSUHVVLQJWKH
6DYHEXWWRQ
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
</head>
<body>
<div data-role="page" id="notes-page">
<div data-role="header" data-position="inline">
<a href="index.html" data-icon="delete">Cancel</a>
<h1>Your Thoughts?</h1>
<a onClick="return saveNotes()" href="#"
data-icon="check" data-theme="b">Save</a>
</div>

<form action="notes.html" method="post">


<textarea name="notes" rows="30" cols="10"></textarea>
</form>

<div data-role="footer" data-position="fixed">


<div data-role="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="map.html">Map</a></li>
<li><a href="compass.html">Compass</a></li>
<li><a href="list.html">List</a></li>
<li><a href="contacts.html">Contacts</a></li>
<li><a href="photos.html">Photos</a></li>
<li><a href="notify.html">Notify</a></li>
<li><a href="notes.html"
class="ui-btn-active">Notes</a></li>
</ul>
</div>
</div>

<script type="text/javascript" charset="utf-8"


src="scripts/notes.js"></script>
</div>
</body>
</html>

$WWKHERWWRPWKLVILOHLQFOXGHVD-DYD6FULSWILOHFDOOHGQRWHVMV&UHDWHWKLVILOHQRZLQ
\RXUDVVHWVZZZVFULSWVGLUHFWRU\
var fileWriter;

function onNotesLoad() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSComplete, fail);
}

function onFSComplete(fileSystem) {
// Load the notes.txt file, create it if it doesn't exist
fileSystem.root.getFile("notes.txt", {create: true}, onFileEntryComplete, fail);
}

Storing Data to the Device | 51

www.it-ebooks.info
function onFileEntryComplete(fileEntry) {
// set up the fileWriter
fileEntry.createWriter(onFileWriterComplete, fail);
}

function onFileWriterComplete(fileWriter) {
// store the fileWriter in a
// global variable so we have it
// when the user presses save
fileWriter = fileWriter;
}

function saveNotes() {
// make sure the fileWriter is set
if (fileWriter != null) {
// create an oncomplete write function
// that will redirect the user
fileWriter.onwrite = function(evt) {
alert("Saved successfully");
$.mobile.changePage("index.html");
};

var form = document.getElementsByTagName('form')[0].elements;


var notes = form.notes.value;

// save the notes


fileWriter.write(notes);
} else {
alert("There was an error trying to save the file");
}

return false;
}

function fail(error) {
alert(error.code);
}

:KHQWKHonNotesLoadIXQFWLRQLVH[HFXWHGE\WKHFDOOEDFNDQDV\QFKURQRXVUHTXHVW
LVPDGHWRRSHQDSHUVLVWHQWILOHV\VWHPFRQQHFWLRQ:KHQWKLVDFWLRQLVFRPSOHWHWKH
onFSCompleteIXQFWLRQLVFDOOHG7KH fileSystemSDUDPHWHULVD DirectoryEntryREMHFW
WKDWLVXVHGWRRSHQDILOHFDOOHGQRWHVW[WLQWKHURRWGLUHFWRU\,IWKHILOHGRHVQRWDOUHDG\
H[LVW LW ZLOO EH FUHDWHG :KHQ WKH ILOH KDV ORDGHG VXFFHVVIXOO\ WKH
onFileEntryCompleteIXQFWLRQLVFDOOHG
7KH onFileEntryComplete IXQFWLRQ UHFHLYHV D fileEntry SDUDPHWHU ZKLFK LV D
FileEntryREMHFW7KLVREMHFWLVWKHQXVHGWRFUHDWHDQREMHFWRIWKH fileWriterFODVV
7KHREMHFWLVVWRUHGLQWKHfileWriterJOREDOYDULDEOHVRWKDWWKHsaveNotesIXQFWLRQFDQ
XVHDQGVDYHWKHFRQWHQWVWRLW

52 | The Recipes

www.it-ebooks.info
:KHQWKHZULWHDFWLRQKDVEHHQFRPSOHWHG DIWHUWKHXVHUSUHVVHV6DYH DVXFFHVVPHV
VDJHLVGLVSOD\HGDQGWKHXVHULVUHGLUHFWHGEDFNWRWKHLQGH[SDJH7KLVDFWLRQRFFXUV
LQVLGHRIWKHonwriteDQRQ\PRXVIXQFWLRQWKDWDSSHDUVZLWKLQWKHsaveNotesIXQFWLRQ

See Also
£5HDGLQJ'DWDIURPWKH'HYLFH¤RQSDJH

Reading Data from the Device


Problem
<RXZDQW\RXUDSSOLFDWLRQWRUHDGDQH[LVWLQJILOHDQGGLVSOD\WKHFRQWHQWVLQDIRUP
IRUIXUWKHUHGLWLQJ

Solution
8VLQJD FileEntryREMHFWUHWULHYHD FileREMHFWWKDWFDQEH readAsDataURLRU readAs
TextZKLFKZLOOUHWXUQGDWDDVDEDVHHQFRGHGXUORUDVWH[WUHVSHFWLYHO\

Discussion
7RUHDGWKHQRWHVW[WILOHWKDWZDVFUHDWHGLQWKHODVWUHFLSHDQGSRSXODWHWKHtextarea
ZLWKLWVFRQWHQWVDIHZXSGDWHVQHHGWRRFFXULQVLGHWKHH[LVWLQJDVVHWVZZZVFULSWV
QRWHVMVILOH
var fileWriter;

function onNotesLoad() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSComplete, fail);
}

function onFSComplete(fileSystem) {
// Load the notes.txt file, create it if it doesn't exist
fileSystem.root.getFile("notes.txt", {create: true}, onFileEntryComplete, fail);
}

function onFileEntryComplete(fileEntry) {
// read the file to preload content
fileEntry.file(onFileReadComplete, fail);

// set up the fileWriter


fileEntry.createWriter(onFileWriterComplete, fail);
}

function onFileReadComplete(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {

Reading Data from the Device | 53

www.it-ebooks.info
// load it into the form
var form = document.getElementsByTagName('form')[0].elements;
form.notes.value = evt.target.result;
};
reader.readAsText(file);
}

function onFileWriterComplete(fileWriter) {
// store the fileWriter in a
// global variable so we have it
// when the user presses save
fileWriter = fileWriter;
}

function saveNotes() {
// make sure the fileWriter is set
if (fileWriter != null) {
// create an oncomplete write function
// that will redirect the user
fileWriter.onwrite = function(evt) {
alert("Saved successfully");
$.mobile.changePage("index.html");
};

var form = document.getElementsByTagName('form')[0].elements;


var notes = form.notes.value;

// save the notes


fileWriter.write(notes);
} else {
alert("There was an error trying to save the file");
}

return false;
}

function fail(error) {
alert(error.code);
}

%HFDXVHRIDOORIWKHZRUNGRQHLQWKHSUHYLRXVUHFLSHRQO\WZRVPDOODGGLWLRQVZHUH
PDGHKHUH)LUVWO\LQVLGHRIWKHonFileEntryCompleteIXQFWLRQWKHILOHLVORDGHGLQWRD
)LOH REMHFW YLD WKLV FDOO fileEntry.file(onFileReadComplete, fail) :KHQ WKH File
REMHFWLVORDGHGWKHonFileReadCompleteIXQFWLRQLVFDOOHG
7KHonFileReadCompleteIXQFWLRQFUHDWHVDQHZFileReaderREMHFWDQGUHDGVWKHILOHDV
WH[W$QDQRQ\PRXVIXQFWLRQLVXVHGZKHQreader.onloadendKDVILQLVKHGUHDGLQJWKH
ILOH $W WKLV SRLQW WKH FRQWHQWV RI WKH ILOH DUH VHW LQ WKH textarea IRUP ILHOG QDPHG
notesDOORZLQJWKHXVHUWRPRGLI\DQ\H[LVWLQJQRWHV

See Also
£6WRULQJ'DWDWRWKH'HYLFH¤RQSDJH

54 | The Recipes

www.it-ebooks.info
Extending PhoneGap with Plug-ins
Problem
<RXZDQWWRDGGDGGLWLRQDOIXQFWLRQDOLW\WR\RXUDSSOLFDWLRQIRUDVSHFLILFGHYLFHWKDW
WKH3KRQH*DSOLEUDU\FXUUHQWO\GRHVQ¦WVXSSRUW

Solution
&UHDWHDFXVWRPSOXJLQWKDWLVDGGHGWR\RXUDSSOLFDWLRQDQGLQYRNHLWZLWK-DYD6FULSW
YLDWKHwindow.pluginFRPPDQG

Discussion
,QWKLVH[DPSOH,DPJRLQJWRH[WHQGWKH3KRQH*DSOLEUDU\E\FUHDWLQJDQGXVLQJDQ
$QGURLGSOXJLQZLWKWKHDSSOLFDWLRQ7KHJRDORIWKLVSOXJLQZLOOEHWRUHDGDQ566
IHHGDQGSDUVHWKH;0/LQWRDQDUUD\RI JSONObjectREMHFWVWKDWZLOOEHRXWSXWWHGLQ
WKHH[LVWLQJ3KRQH*DSDSSOLFDWLRQ$V,PHQWLRQHGLQWKHSUHIDFH,DPGHYHORSLQJRQ
:LQGRZVXVLQJ(FOLSVHVRWKHSOXJLQZLOOEHIRUWKH$QGURLGRQO\EXWLPSOHPHQWLQJ
WKHSOXJLQLVSODWIRUPLQGHSHQGHQWEHFDXVHLWLVGRQHYLD-DYD6FULSW,QRWKHUZRUGV
LI\RXZHUHWRGRZQORDGDQL3KRQHSOXJLQLWFRXOGEHLPSOHPHQWHGLQDVLPLODUIDVKLRQ
7RFUHDWHDSOXJLQDQHZ$QGURLG3URMHFWPXVWEHFUHDWHG,Q(FOLSVHVHOHFW)LOHൺ
1HZൺ$QGURLG3URMHFW,DPJRLQJWRQDPHWKHSURMHFWXMLParser)RUWKH%XLOG7DUJHW
VHOHFWWKHODWHVW$QGURLG$3,7KH£$SSOLFDWLRQQDPH¤ZLOOEH XMLParserPlugin,¦YH
FUHDWHGWKHSDFNDJHDVcom.webistrate.phonegap.plugin.xmlparser XSGDWHDVQHHGHG
IRU\RXUSDFNDJH $QGILQDOO\,XQFKHFNHG&UHDWH$FWLYLW\
2QFHWKHQHZSURMHFWLVDGGHG\RXDOVRQHHGWRDGGWKH3KRQH*DSOLEUDU\WR\RXU
SURMHFW-XVWOLNHGXULQJWKHLQLWLDOVHWXS\RXFDQFRS\WKHSKRQHJDSMDUILOHWRDQHZ
OLEVGLUHFWRU\DQGDGGLWWRWKH%XLOG&RQILJXUDWLRQ
1RZLW¦VWLPHWRFUHDWHVRPH-DYDFRGH VLQFHWKDWLVKRZ\RXFUHDWHQDWLYH$QGURLG
DSSOLFDWLRQV 
$FRUHFODVVLVQHHGHGWKDWZLOOUHVSRQGWRFDOOVIURP-DYD6FULSW$GGDQHZFODVVFDOOHG
;0/3DUVHU3OXJLQMDYDWR\RXUSURMHFW7KLVFODVVZLOOH[WHQG3KRQH*DS¦VPluginFODVV
7KHFRQWHQWVRIWKLVFODVVDUHDVIROORZV
package com.webistrate.phonegap.plugin.xmlparser;

import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;

Extending PhoneGap with Plug-ins | 55

www.it-ebooks.info