I am new to phone gap.I am referring examples from http://docs.phonegap.com/.
But when i am trying to execute the program given in http://docs.phonegap.com/en/1.8.1/cordova_contacts_contacts.md.html#Contacts
the onDeviceReady function is not getting loaded.
**Case 1:**
**Here is the code(index.html file):**
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.8.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() {
alert("onDeviceReady");
console.log("onDeviceReady");
// create
var contact = navigator.contacts.create();
contact.displayName = "Plumber";
contact.nickname = "Plumber"; //specify both to support all devices
var name = new ContactName();
name.givenName = "Jayshree";
name.familyName = "Barkur";
contact.name = name;
// save
contact.save(onSaveSuccess,onSaveError);
// clone
//var clone = contact.clone();
// clone.name.givenName = "John";
// console.log("Original contact name = " + contact.name.givenName);
//console.log("Cloned contact name = " + clone.name.givenName);
// remove
//contact.remove(onRemoveSuccess,onRemoveError);
}
// onSaveSuccess: Get a snapshot of the current contacts
//
function onSaveSuccess(contact) {
alert("Save Success");
}
// onSaveError: Failed to get the contacts
//
function onSaveError(contactError) {
alert("Error = " + contactError.code);
}
// onRemoveSuccess: Get a snapshot of the current contacts
//
function onRemoveSuccess(contacts) {
alert("Removal Success");
}
// onRemoveError: Failed to get the contacts
//
function onRemoveError(contactError) {
alert("Error = " + contactError.code);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Create Contacts</p>
</body>
</html>
I am executing this program in eclipse(Android 4.4).On execution the emmulator only shows
**Examples**
**Create Contacts**
And nothing happens after that i.e the the onDeviceReady method is not called and neither the other callback functions are called.
**Case 2:**
When i am adding an extra line in the program i.e. <p>Add Contact</p> in the body section,The contacts are getting added.
But
function onSaveSuccess(contact) {
alert("Save Success");
}
does not works for me.
**Here goes my code(index.html file):**
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.8.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() {
alert("onDeviceReady");
console.log("onDeviceReady");
// create
var contact = navigator.contacts.create();
contact.displayName = "Plumber";
contact.nickname = "Plumber"; //specify both to support all devices
var name = new ContactName();
name.givenName = "Jayshree";
name.familyName = "Barkur";
contact.name = name;
// save
contact.save(onSaveSuccess,onSaveError);
// clone
//var clone = contact.clone();
// clone.name.givenName = "John";
// console.log("Original contact name = " + contact.name.givenName);
//console.log("Cloned contact name = " + clone.name.givenName);
// remove
//contact.remove(onRemoveSuccess,onRemoveError);
}
// onSaveSuccess: Get a snapshot of the current contacts
//
function onSaveSuccess(contact) {
alert("Save Success");
}
// onSaveError: Failed to get the contacts
//
function onSaveError(contactError) {
alert("Error = " + contactError.code);
}
// onRemoveSuccess: Get a snapshot of the current contacts
//
function onRemoveSuccess(contacts) {
alert("Removal Success");
}
// onRemoveError: Failed to get the contacts
//
function onRemoveError(contactError) {
alert("Error = " + contactError.code);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Create Contacts</p>
<p>Add Contact</p>
</body>
</html>
Kindly let me know the reason behind this and suggest some solution to solve this problem.
Thanks in advance
Seems like you havent added the cordova library
download the same from here and add cordova-1.8.0.js to the www folder
Try this :
Enable the emulator GPU.
In Eclipse go to Window -> AVD Manager select your AVD and click "Edit".
Check "Use Host GPU" box, then save and restart your AVD.
Hope this helps.
Related
I'm trying to implement the login action using the twitter acount in my cordova app.
I have found a script using Childbrowser.js file to do it but it's not supported anymore so that I am trying to do it using the inappBrowser plugin instead of the childbrowser.
I succeeded in opening the login interface but after the login it redirect me to a web page. How can I redirect to my html local page? can I get ignore the redirect url and just get the access token?
this is the code that I am using:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" charset="utf-8" src="js/codebird.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jsOAuth-1.3.1.js"></script>
<script type="text/javascript">
function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var root = this;
//var cb = new Codebird;
var cb = window.open();
if(!localStorage.getItem(twitterKey)){
$("#loginBtn").show();
$("#logoutBtn").hide();
}
else {
return ('here test');
$("#loginBtn").hide();
$("#logoutBtn").show();
}
if (cb != null) {
cb.addEventListener('loadstart', function(event) { onOpenExternal(); });
cb.addEventListener('loadstop', function(event) { onOpenExternal();});
cb.addEventListener('exit', function(event) { onCloseBrowser() });
}
}
function onCloseBrowser() {
alert('onCloseBrowser');
console.log("onCloseBrowser!");
}
function locChanged(loc) {
alert('locChanged');
console.log("locChanged!");
}
function onOpenExternal() {
alert('onOpenExternal');
console.log("onOpenExternal!");
}
</script>
<!--Below is the code for twitter-->
<script>
// GLOBAL VARS
var oauth; // It Holds the oAuth data request
var requestParams; // Specific param related to request
var options = {
consumerKey: 'xxxxx', // YOUR Twitter CONSUMER_KEY
consumerSecret: 'xxxxxx', // YOUR Twitter CONSUMER_SECRET
callbackUrl: "http://127.0.0.1:81/" }; // YOU have to replace it on one more Place
var twitterKey = "twtrKey"; // This key is used for storing Information related
var Twitter = {
init:function(){
// Apps storedAccessData , Apps Data in Raw format
var storedAccessData, rawData = localStorage.getItem(twitterKey);
// here we are going to check whether the data about user is already with us.
if(localStorage.getItem(twitterKey) !== null){
// when App already knows data
storedAccessData = JSON.parse(rawData); //JSON parsing
//options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin
// javascript OAuth take care of everything for app we need to provide just the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("USERNAME: " + entry.screen_name);
}
);
}
else {
// we have no data for save user
oauth = OAuth(options);
oauth.get('https://api.twitter.com/oauth/request_token',
function(data) {
requestParams = data.text;
cb=window.open('https://api.twitter.com/oauth/authorize?'+data.text); // This opens the Twitter authorization / sign in page
cb.addEventListener('loadstop', function(loc){alert('stop: ' + loc.url);
// Twitter.success(loc);
});
},
function(data) {
console.log("ERROR: "+data);
}
);
}
},
/*
When ChildBrowser's URL changes we will track it here.
We will also be acknowledged was the request is a successful or unsuccessful
*/
success:function(loc){
alert('ok entred');
// Here the URL of supplied callback will Load
/*
Here Plugin will check whether the callback Url matches with the given Url
*/
if (loc.indexOf("http://127.0.0.1:81/?") >= 0) {
// Parse the returned URL
var index, verifier = '';
var params = loc.substr(loc.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_verifier') {
verifier = y[1];
}
}
// Here we are going to change token for request with token for access
/*
Once user has authorised us then we have to change the token for request with token of access
here we will give data to localStorage.
*/
oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier='+verifier+'&'+requestParams,
function(data) {
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
}
$('#oauthStatus').html('<span style="color:green;">Success!</span>');
$('#stage-auth').hide();
$('#stage-data').show();
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
// Saving token of access in Local_Storage
var accessData = {};
accessData.accessTokenKey = accessParams.oauth_token;
accessData.accessTokenSecret = accessParams.oauth_token_secret;
// Configuring Apps LOCAL_STORAGE
console.log("TWITTER: Storing token key/secret in localStorage");
localStorage.setItem(twitterKey, JSON.stringify(accessData));
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("TWITTER USER: "+entry.screen_name);
$("#welcome").show();
document.getElementById("welcome").innerHTML="welcome " + entry.screen_name;
successfulLogin();
// Just for eg.
app.init();
},
function(data) {
console.log("ERROR: " + data);
}
);
// Now we have to close the child browser because everthing goes on track.
window.plugins.childBrowser.close();
},
function(data) {
alert('rr');
console.log(data);
}
);
}
else {
// Just Empty
}
},
tweet:function(){
var storedAccessData, rawData = localStorage.getItem(twitterKey);
storedAccessData = JSON.parse(rawData); // Paring Json
options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login
// javascript OAuth will care of else for app we need to send only the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
Twitter.post();
}
);
},
/*
We now have the data to tweet
*/
post:function(){
var theTweet = $("#tweet").val(); // You can change it with what else you likes.
oauth.post('https://api.twitter.com/1/statuses/update.json',
{ 'status' : theTweet, // javascript OAuth encodes this
'trim_user' : 'true' },
function(data) {
var entry = JSON.parse(data.text);
console.log(entry);
// just for eg.
done();
},
function(data) {
console.log(data);
}
);
}
}
function done(){
$("#tweet").val('');
}
function successfulLogin(){
$("#loginBtn").hide();
$("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();
}
function logOut(){
//localStorage.clear();
window.localStorage.removeItem(twitterKey);
document.getElementById("welcome").innerHTML="Please Login to use this app";
$("#loginBtn").show();
$("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();
}
</script>
<!--Code for Twitter ends here-->
</head>
<body onload="onBodyLoad()">
<h4>Oodles Twitter App</h4>
<table border="1">
<tr>
<th>Login using Twitter</th>
<th>
<button id="loginBtn" onclick="Twitter.init()">Login</button>
<button id="logoutBtn" onclick="logOut();">Logout</button>
</th>
</tr>
<tr id="tweetText" style="display:none;">
<td colspan="2"><textarea id="tweet" style="display:none;"></textarea></td>
</tr>
<tr id="tweetBtn" style="display:none;">
<td colspan="2" align="right">
<button id="tweeter" onclick="Twitter.tweet();" style="display:none">Tweet</button>
</td>
</tr>
<tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
</table>
</body>
Actually there is error in your code you have to fix it:
the https://api.twitter.com/1/account/verify_credentials.json?skip_status=true' is no more used change it to 1.1.
also change the way you close your inappbrowser.
this code works for me try it:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" charset="utf-8" src="js/codebird.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jsOAuth-1.3.1.js"></script>
<script type="text/javascript">
function onBodyLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var root = this;
//var cb = new Codebird;
var cb = window.open();
if(!localStorage.getItem(twitterKey)){
$("#loginBtn").show();
$("#logoutBtn").hide();
}
else {
retiurn ('hhhh');
$("#loginBtn").hide();
$("#logoutBtn").show();
}
if (cb != null) {
cb.addEventListener('loadstart', function(event) { onOpenExternal(); });
cb.addEventListener('loadstop', function(event) { onOpenExternal();});
cb.addEventListener('exit', function(event) { onCloseBrowser() });
}
}
function onCloseBrowser() {
alert('onCloseBrowser');
console.log("onCloseBrowser!");
}
function locChanged(loc) {
alert('locChanged');
console.log("locChanged!");
}
function onOpenExternal() {
alert('onOpenExternal');
console.log("onOpenExternal!");
}
</script>
<!--Below is the code for twitter-->
<script>
// GLOBAL VARS
var oauth; // It Holds the oAuth data request
var requestParams; // Specific param related to request
var options = {
consumerKey: 'xxxxx', // YOUR Twitter CONSUMER_KEY
consumerSecret: 'xxxxx', // YOUR Twitter CONSUMER_SECRET
callbackUrl: "http://127.0.0.1:81/" }; // YOU have to replace it on one more Place
var twitterKey = "twtrKey"; // This key is used for storing Information related
var Twitter = {
init:function(){
// Apps storedAccessData , Apps Data in Raw format
var storedAccessData, rawData = localStorage.getItem(twitterKey);
// here we are going to check whether the data about user is already with us.
if(localStorage.getItem(twitterKey) !== null){
// when App already knows data
storedAccessData = JSON.parse(rawData); //JSON parsing
//options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin
// javascript OAuth take care of everything for app we need to provide just the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("USERNAME: " + entry.screen_name);
}
);
}
else {
// we have no data for save user
oauth = OAuth(options);
oauth.get('https://api.twitter.com/oauth/request_token',
function(data) {
requestParams = data.text;
cb=window.open('https://api.twitter.com/oauth/authorize?'+data.text,'_blank', 'location=no'); // This opens the Twitter authorization / sign in page
cb.addEventListener('loadstop', function(loc){//alert('stop: ' + loc.url);
Twitter.success(loc);
});
},
function(data) {
console.log("ERROR: "+data);
}
);
}
},
/*
When ChildBrowser's URL changes we will track it here.
We will also be acknowledged was the request is a successful or unsuccessful
*/
success:function(loc){
// alert(loc.url);
// Here the URL of supplied callback will Load
/*
Here Plugin will check whether the callback Url matches with the given Url
*/
if (loc.url.indexOf("http://127.0.0.1:81/?") >-1) {
// Parse the returned URL
var index, verifier = '';
var params = loc.url.substr(loc.url.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_verifier') {
verifier = y[1];
}
}
// Here we are going to change token for request with token for access
/*
Once user has authorised us then we have to change the token for request with token of access
here we will give data to localStorage.
*/
oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier='+verifier+'&'+requestParams,
function(data) {
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
}
// alert(verifier)
$('#oauthStatus').html('<span style="color:green;">Success!</span>');
$('#stage-auth').hide();
$('#stage-data').show();
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
// Saving token of access in Local_Storage
var accessData = {};
accessData.accessTokenKey = accessParams.oauth_token;
accessData.accessTokenSecret = accessParams.oauth_token_secret;
// Configuring Apps LOCAL_STORAGE
console.log("TWITTER: Storing token key/secret in localStorage");
localStorage.setItem(twitterKey, JSON.stringify(accessData));
oauth.get('https://api.twitter.com/1.1/account/verify_credentials.json?skip_status=true',
function(data) {
// alert('key'+twitterKey);
var entry = JSON.parse(data.text);
console.log("TWITTER USER: "+entry.screen_name);
$("#welcome").show();
document.getElementById("welcome").innerHTML="welcome " + entry.screen_name;
successfulLogin();
// Just for eg.
app.init();
},
function(data) {
console.log("ERROR: " + data);
}
);
// Now we have to close the child browser because everthing goes on track.
cb.close();
},
function(data) {
// alert('rr');
console.log(data);
}
);
}
else {
// Just Empty
}
},
tweet:function(){
var storedAccessData, rawData = localStorage.getItem(twitterKey);
storedAccessData = JSON.parse(rawData); // Paring Json
options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login
// javascript OAuth will care of else for app we need to send only the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1.1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
Twitter.post();
}
);
},
/*
We now have the data to tweet
*/
post:function(){
var theTweet = $("#tweet").val(); // You can change it with what else you likes.
oauth.post('https://api.twitter.com/1.1/statuses/update.json',
{ 'status' : theTweet, // javascript OAuth encodes this
'trim_user' : 'true' },
function(data) {
var entry = JSON.parse(data.text);
console.log(entry);
// just for eg.
done();
},
function(data) {
console.log(data);
}
);
}
}
function done(){
$("#tweet").val('');
}
function successfulLogin(){
$("#loginBtn").hide();
$("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();
}
function logOut(){
//localStorage.clear();
window.localStorage.removeItem(twitterKey);
document.getElementById("welcome").innerHTML="Please Login to use this app";
$("#loginBtn").show();
$("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();
}
</script>
<!--Code for Twitter ends here-->
</head>
<body onload="onBodyLoad()">
<h4>Oodles Twitter App</h4>
<table border="1">
<tr>
<th>Login using Twitter</th>
<th>
<button id="loginBtn" onclick="Twitter.init()">Login</button>
<button id="logoutBtn" onclick="logOut();">Logout</button>
</th>
</tr>
<tr id="tweetText" style="display:none;">
<td colspan="2"><textarea id="tweet" style="display:none;"></textarea></td>
</tr>
<tr id="tweetBtn" style="display:none;">
<td colspan="2" align="right">
<button id="tweeter" onclick="Twitter.tweet();" style="display:none">Tweet</button>
</td>
</tr>
<tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
</table>
</body>
I recently updated the version of PhoneGap/Cordova I was using to the most recent. There is a page in my app that keeps throwing the following error every time it loads.
Uncaught Reference Error: google is not defined
I tried to use a sample webpage directly from the google developer's site to try and narrow down my options, and still got the same error when trying to load that page on my phone. (found here: https://developers.google.com/maps/documentation/javascript/examples/map-simple). I should note, when running this webpage from google as an .HTML file in Chrome on my desktop it worked fine.
I have also tried to use the solution found here: Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX
however the initialize method was never even called, which leads me to believe it's a problem with my script tag that I'm still missing.
As far as I can tell, I am using proper script calls in my HTML:
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?<KEY>&sensor=false"></script>
and the javascript code that is crashing is as follows:
origins[0] = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
The full code is here:
<!DOCTYPE HTML>
<html>
<head>
<title>MASH Locations</title>
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="styles/layout.css" />
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=(myAppKey)&sensor=false"></script>
<script type="text/javascript" charset="utf-8" src="Util.js"></script>
<script type="text/javascript" charset="utf-8" src="QuickSort.js"></script>
<script type="text/javascript" charset="utf-8" src="Location.js"></script>
<script type="text/javascript">
var origins, destinations;
var BORDER_ROW = '<tr><td colspan="3" class="location-result-border"> </td></tr>';
var RESULT_FORMAT = '<tr><td id="result_{7}" class="location-result-row" onclick="onLocationResultClick(\'{0}\', \'{1}\', \'{2}\', \'{3}\', \'{4}\', \'http://cloud.intelligentbits.net/mash/images/{5}\', \'{6}\')">'
+ '<table class="{8}">'
+ '<tr><td class="location-result-distance" rowspan="3"><div>{9}</div>miles</td>'
+ '<td class="location-result-logo" rowspan="3"><img src="http://sqldb.intelligentbits.net/mash/images/{5}" alt="{0}" /></td>'
+ '<td class="location-result-name">{0}</td></tr>'
+ '<tr><td class="location-result-address">{10}</td></tr>'
+ '<tr><td class="location-result-city">{11}</td></tr></table></td></tr>';
function onLoad()
{
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is ready
function onDeviceReady()
{
navigator.geolocation.getCurrentPosition(onPositionFound, onPositionError);
}
function onPositionFound(position)
{
// get the current location
origins = new Array();
origins[0] = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
document.getElementById('finding').innerText = 'Finding our locations...';
readFile('http://sqldb.intelligentbits.net/mash/locations.txt', onLocationsFound);
}
// onPositionError Callback receives a PositionError object
function onPositionError(error)
{
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function onLocationsFound(text)
{
if (text == null || text.length == 0)
{
document.getElementById('finding').innerText = 'An error occurred.';
return;
}
// split the text into lines (one line per location)
var lines = text.split(/\r?\n/g);
if (lines.length == 0)
{
document.getElementById('finding').innerText = 'An error occurred.';
return;
}
// destinations
destinations = new Array();
var locIdx = 0;
// iterate over lines/locations
for (var i = 0; i < lines.length; ++i)
{
// split into fields
var loc = new Location();
var fields = lines[i].split(';');
for (var j = 0; j < fields.length; ++j)
{
// split fields into name and value
var tokens = fields[j].split('=');
if (tokens.length != 2) continue;
switch (tokens[0].toUpperCase())
{
case 'NAME':
loc.Name = tokens[1];
break;
case 'ADDRESS':
loc.StreetAddress = tokens[1];
break;
case 'CITY':
loc.City = tokens[1];
break;
case 'STATE':
loc.Region = tokens[1];
break;
case 'POSTAL':
loc.PostalCode = tokens[1];
break;
case 'PHONE':
loc.Phone = tokens[1];
break;
case 'HOURS':
loc.Hours = tokens[1];
break;
case 'LOGO':
loc.LogoFileName = tokens[1];
break;
case 'EMAIL':
loc.Email = tokens[1];
break;
}
}
// save the destination
destinations[locIdx++] = loc;
}
if (destinations.length == 0)
document.getElementById('finding').innerText = 'An error occurred.';
else
calculateDistances(origins, destinations);
}
function calculateDistances(orig, dest) {
// the passed-in destinations are arrays of Location objects; Google Maps wants strings
var destStrings = new Array();
for (var i = 0; i < dest.length; ++i)
destStrings[i] = dest[i].ToAddressString();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: orig,
destinations: destStrings,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, onDistancesFound);
}
function onDistancesFound(response, status)
{
if (status != google.maps.DistanceMatrixStatus.OK)
{
alert('Error was: ' + status);
}
else
{
// get the place we'll store the list
var p = document.getElementById('finding');
var table = document.getElementById('location-results');
var orig = response.originAddresses;
var dest = response.destinationAddresses;
p.innerText = 'Tap a location for more options.';
// iterate over origins
for (var i = 0; i < orig.length; ++i) {
var results = response.rows[i].elements;
// iterate over destinations
for (var j = 0; j < results.length; ++j) {
// split the location into the amount and units
var distance = results[j].distance.text.Trim().split(' ');
// update the locations
destinations[j].DistanceFromUser = parseFloat(distance[0]);
destinations[j].DistanceUnits = distance[1];
destinations[j].TimeFromUser = results[j].duration.text;
}
}
// sort the distances
QuickSort(destinations, 'DistanceFromUser');
// print the results
var tablerows = '';
for (var i = 0; i < destinations.length; ++i) {
var loc = destinations[i];
tablerows += RESULT_FORMAT.Format(loc.Name, loc.Phone, loc.ToAddressString(), loc.ToTwoLineAddressString(),
loc.Hours, loc.LogoFileName, loc.Email, i, 'location-result-' + ((i + 1) % 2 == 0 ? 'even' : 'odd'),
loc.DistanceFromUser, loc.StreetAddress, loc.City);
}
tablerows += '<tr><td><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/></td></tr>';
// append the rows
table.innerHTML += tablerows;
}
}
function onLocationResultClick(name, phone, address, displayAddress, hours, imageUrl, email)
{
// save the name and address to local storage for the directions
window.localStorage.setItem('location-position', address);
window.localStorage.setItem('location-address', displayAddress);
window.localStorage.setItem('location-title', name);
window.localStorage.setItem('location-hours', hours);
window.localStorage.setItem('location-phone', phone);
window.localStorage.setItem('location-imageUrl', imageUrl);
window.localStorage.setItem('location-contact', email);
// call link
window.location = 'location.html';
}
</script>
</head>
<body onload="onLoad()">
<h1>
<a href="index.html" class="back">
<div>
<span></span>
</div> <span class="text">Back</span>
</a> Nearest Locations
</h1>
<div id="location-results-wrapper">
<h1 style="position: static; width: 94%;">
<a href="#" class="back">
<div>
<span></span>
</div> <span class="text">Back</span>
</a> #
</h1>
<table id="location-results">
<tr>
<td id="finding" style="vertical-align: top;">Finding your
location...</td>
<tr>
</table>
</div>
</body>
</html>
and the exact error log:
06-27 09:06:00.624: E/Web Console(15020): Uncaught ReferenceError: google is not defined at file:///android_asset/www/locations.html:41
Try these
Check your internet connection
Keep Map API script tag as a first script tag in your code.
i.e Before loading any other javascripts load map API.
Hope this helps.
I found my solution. When running the update command for PhoneGap, the cordova.js and config.xml files were not copied over into the my project. I'm not sure if this is intentional (I easily could have missed documentation on this somewhere), but it seemed unintuitive at the time. After manually copying these two files into my project, everything worked.
When u're using multiple HTML pages. use the google API javascript on the main page(index). the Ajax will not relaod the map when its refreshed.
If google map api is not defined then it too can cause the problem.
Since i missed out while getting the address from latitude and longitude.
I am trying to create a database using phonegap's api:
In order to do this I have used the following html:
<!DOCTYPE HTML>
<html>
<head>
<title>Cordova</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.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 db = window.openDatabase("test", "1.0", "Test DB", 1000000);
alert("database created");
}
</script>
</head>
<body>
<form name="input" action="html_form_action.asp" method="get">
<input type="submit" value="Create Db" />
</form>
</body>
</html>
The buttone doesnt do anyting. The idea is that when the app starts I'm supposed to get confirmation that a database has been created. However this is not happening. Please help...
**Hi check whether Deviceready fires or not then try this **
function onDeviceReady() {
alert("onDeviceReady");
try {
if (!window.openDatabase) {
alert('Browser does not Support this');
} else {
var shortName = 'DbName';
var version = '1.0';
var displayName = 'DBName';
var maxSize = 100000; // in bytes
openDatabase(shortName, version, displayName, maxSize);
alert('DB created');
}
} catch(e) {
if (e == 2) {
// Version mismatch..
console.log("Invalid database version.");
} else {
console.log("Unknown error "+ e +".");
}
return;
}
}
I think there is problem in your js location path . I run your code and i didn't get any error.
Please check your path of your cordova.js . I think you put that js in js folder of assets/www/js
I dont think 'alert()' works inside a webview as-is. Try console.log() instead to output a message (if you are using eclipse), or some other method - perhaps changing the content of a div - to show you the results.
In my application, i want to insert the value in the table. i have created the databse in onDeviceReady() method in the index.html file.
<!DOCTYPE html>
<!-- Auto Generated with Sencha Architect -->
<!-- Modifications to this file will be overwritten. -->
<html>
<head>
<meta name="generator" content="HTML Tidy, see www.w3.org">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Teritree</title>
<script type="text/javascript" id="phonegap" src=
"cordova-2.0.0.js">
</script>
<script type="text/javascript" src="barcodescanner.js">
</script>
<script src="sencha-touch-all.js" type="text/javascript">
</script>
<link rel="stylesheet" type="text/css" href="app.css">
<script type="text/javascript" src="app/Ext.ux.touch.Rating.js">
</script>
<script type="text/javascript" src="app/app.js">
</script>
<script type="text/javascript">
Ext.Loader.setConfig({ disableCaching: false });
Ext.Ajax.setDisableCaching(false);
</script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
var mydb;
// Wait for PhoneGap to connect with the device
function onLoad() {
document.addEventListener("deviceready",onDeviceReady,false);
}
// PhoneGap is ready to be used!
function onDeviceReady() {
console.log("it is in ondevice ready method..");
mydb = window.openDatabase("teritreeDb", "1.0", "TestDB", 10000);
console.log("it is in ondevice ready method..1");
mydb.transaction(populateDB, errorCB, successCB);
console.log("it is in ondevice ready method..2");
}
function populateDB(tx) {
console.log("it is in populateDB----------1");
tx.executeSql('DROP TABLE IF EXISTS DEMO', function () {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)', function () {
console.log("Table created");
});
});
// Transaction error callback
//
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
// Transaction success callback
//
function successCB() {
alert("success!");
}
}
</script>
<script type="text/javascript">
if (!Ext.browser.is.WebKit) {
alert("The current browser is unsupported.\n\nSupported browsers:\n" +
"Google Chrome\n" +
"Apple Safari\n" +
"Mobile Safari (iOS)\n" +
"Android Browser\n" +
"BlackBerry Browser"
);
}
</script>
</head>
<body>
</body>
</html>
Now i have one signup screen and there in the signup screen i have submit button. So if i click the submit button, all the details should store in the database means in the DEMO table..So in the controller, i am writing the button event,
onSubmitButtonTap : function(button, e, options) {
mydb = window.openDatabase("appDb", "1.0", "Test DB", 1000000);
mydb.transaction(storeCustomerDetails, error, success);
function storeCustomerDetails(tx)
{
tx.executeSql('insert into DEMO (id,data) values("1","Hello")');
tx.executeSql('insert into DEMO (id,data) values("2","Hello World")');
}
function error(){
alert("data is not inserted");
}
function success(){
alert("data is succesfully inserted");
}
},
but it is giving me the alert, data is not inserted.
I followed the link: Phonegap DB Link
Please help..
Use Cordova 2.0.0 and your issue will be solved.. You will be able to see the database you created in the file explorer. Do let me know if it helps you.
Arindam, do not forget by default the executing of the sql is asyncronious. Therefore nobody warranty your sqls will be executed in order you have defined in function populateDB(tx). Eg. it could execute first create than delete...
To be sure in the order you have to define subsequent calls in the callback function
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO', function () {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)', function () {
console.log("Table created");
});
});
}
Cheers, Oleg
I'm working on a mobile application using phoneGap. I'm showing deviceInfo and and it's not working on Android emulator! but works on BlackBerry emulator. I`m using Dreamweaver cs 5.5. Any solution to this issue?
Here is my code:
// invoked when device is ready
function deviceInfo() {
document.getElementById('window.device.platform').innerHTML = 'window.device.platform = ' + window.device.platform;
document.getElementById('window.device.version').innerHTML = 'window.device.version = ' + window.device.version;
document.getElementById('window.device.uuid').innerHTML = 'window.device.uuid = ' + window.device.uuid;
document.getElementById('window.device.phonegap').innerHTML = 'window.device.phonegap = ' + window.device.phonegap;
navigator.network.isReachable("phonegap.com", function(reachability) {
var states = {};
states[NetworkStatus.NOT_REACHABLE] = 'No network connection';
states[NetworkStatus.REACHABLE_VIA_CARRIER_DATA_NETWORK] = 'Carrier data connection';
states[NetworkStatus.REACHABLE_VIA_WIFI_NETWORK] = 'WiFi connection';
document.getElementById('networkStatus').innerHTML = 'isReachable = ' + states[reachability];
},
{ isIpAddress: false });
}
// invoked when application is resumed (brought to foregroud)
function doResume() {
console.log('doResume()');
}
// invoked when application is paused (sent to background)
function doPause() {
console.log('doPause()');
}
// register PhoneGap event listeners when DOM content loaded
function init() {
console.log('init()');
document.addEventListener("deviceready", deviceInfo, true);
document.addEventListener("resume", doResume, false);
document.addEventListener("pause", doPause, false);
}
function unload() {
console.log('unload()');
}
function fail(error) {
navigator.notification.alert(error, null, "Error");
}
On my HTML:<body onload="init()" onunload="unload()">
Make sure the name of the cordova script is spelled correctly:
it may read
<script type="text/javascript" charset="utf-8" src="cordova-1.x.x.js"></script>
where it should read:
<script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>
Make sure that "<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />" is present in AndroidManifest.xml.
I could get rid of this issue when I found out, that the cordova version numbers of my cordova.js and the cordova.jar file didn't match.
Getting both from the same cordova version fixed it for me.
That was a time consuming and stupid mistake on muy side.