Undefined EXEC method in PhoneGap 2.0 - android

When trying to execute a phonegap plugin method, the application raises this error:
TypeError 'undefined' is not a function (evaluating 'cordova.exec( ...
Code included in app:
Javascript plugin link (file settingswrite.js)
window.SettingsWrite = function(objectData, successCallback, failureCallback) {
var options = {};
for (var key in objectData) {
options[key] = objectData[key];
}
cordova.exec(
successCallback,
failureCallback,
'SettingsWrite',
'set',
new Array(options)
);
};
Javascript code to make use of plugin (file app.js)
function setActualPosition() {
// appMap is an application global object
var map = appMap.getMapEdgesProjection();
window.SettingsWrite([{
x: map.minh,
y: map.maxh
}],
function(r){
alert(r);
},
function(e){
alert("Operation error");
console.log('ERROR: ' + e);
});
}
Plugin is declared in config.xml as:
<plugin name="SettingsWrite" value="es.mycompany.cordova.plugin.SettingsWrite"/>
Javascript code is executed index.html (located at assets folder and included into WebView):
<!DOCTYPE html>
<html>
<head>
<title>Test Mobile</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<script src="assets/js/cordova-2.0.0.js"></script>
<script src="assets/js/jquery-1.7.2.min.js"></script>
<script src="assets/js/settingswrite.js"></script>
<script src="assets/js/app.js"></script>
</head>
<body>
<div id="divMapContainer"></div>
</body>
</html>
And the plugin Java class (as defined in Phonegap docs):
public class SettingsWrite extends Plugin {
public static final String ACTION = "set";
#Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
if(ACTION.equals(action)) {
.
.
.
} else {
.
.
.
}
}
The plugin runs in Android 3.1 device and all needed files are correctly included to the project(cordova-2.0.0.js and cordova-2.0.0.jar). May someone help me?

At what point are you calling setActualPosition? Has the deviceready event fired? If it has not fired, you will not have access to the cordova objects.

I was getting the same error as you. There is a fix in this post:
datePicker plugin not working in Phonegap 2.0

Related

Ionic Framework and AngularJS - How to read mobile contacts into application

Below is the code I have tried. When I execute the code below it appears as when I click a button in my application and it is opening device phone book and displaying contacts. When I click on any contact it is picked by application but it should not open device address book but when clicked it should display the contacts of my device in my application. Can anyone suggest me how to do this?
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, r-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="starter" ng-controller="AppCtrl" class="platform-android platform-cordova platform-webview">
<ion-pane>
<ion-header-bar class="bar-stable">
<button class="button" ng-click="pickContact()">Contacts</button>
<h1 class="title">All Contacts</h1>
</ion-header-bar>
<ion-content>
<div class="list">
<a class="item item-thumbnail-left" ng-repeat="contact in data.selectedContacts">
<img src="{{contact.photos[0].value}}" ng-if="contact.photos.length > 0">
<h2>{{contact.displayName}}</h2>
<p ng-if="contact.emails.length > 0">{{contact.emails[0].type}} : {{contact.emails[0].value}}</p>
<p ng-if="contact.phones.length > 0">{{contact.phones[0].type}} : {{contact.phones[0].value}}</p>
</a>
</div>
<p class="padding"></p>
</ion-content>
</ion-pane>
</body>
</html>
Javascript:
angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.service("ContactsService", ['$q',
function($q) {
var formatContact = function(contact) {
return {
"displayName": contact.name.formatted || contact.name.givenName + " " + contact.name.familyName || "Unknown Person",
"emails": contact.emails || [],
"phones": contact.phoneNumbers || [],
"photos": contact.photos || []
};
};
var pickContact = function() {
var deferred = $q.defer();
if (navigator && navigator.contacts) {
navigator.contacts.pickContact(function(contact) {
deferred.resolve(formatContact(contact));
});
} else {
deferred.reject("Hurray!!!!...... No contacts in desktop browser");
}
return deferred.promise;
};
return {
pickContact: pickContact
};
}
])
.controller("AppCtrl", ['$scope', 'ContactsService',
function($scope, ContactsService) {
$scope.data = {
selectedContacts: []
};
$scope.pickContact = function() {
ContactsService.pickContact().then(
function(contact) {
$scope.data.selectedContacts.push(contact);
console.log("Selected contacts=");
console.log($scope.data.selectedContacts);
},
function(failure) {
console.log("Hurray!!!!...... Failed to pick a contact");
}
);
}
}
])
You could try using $cordovaContacts which is a part of the ngCordova (ngCordova needs to be installed). You can install in your app with the command cordova plugin add cordova-plugin-contacts. Then there is a simple function to getting all contacts in your contacts list.
$scope.getAllContacts = function() {
$cordovaContacts.find({filter: '',multiple:true}).then(function(allContacts) {
$scope.contacts = allContacts;
});
};
Note: It seems to be so that the find() function in $cordovaContacts can not be empty. Include ie. a filter in there for it to work.
EDIT:
This is a demonstration of the general structure and functions which you need to make the ngCordova contacts plugin to work.
Here's all my code you'll need in a JSFiddle: https://jsfiddle.net/thepio/osjppoqu/
And then I just call the getAllContacts function using a button click in my app.html file like this:
<button type="button" ng-click="getAllContacts()" class="button button-block button-positive">Get contacts</button>
REMEMBER it only works on a real device, probably not even emulator (haven't tested though). Include the ngCordova in your module. If you're calling the contacts plugin without a click or something remember that it is required that it's only called AFTER the device is ready. In Ionic you can do this with the following:
$ionicPlatform.ready(function() {
// Call the plugin here
});

Ionic Cordova AngularJs : Why Facebook share works in Ionic serve (browser) but not pop-up display in Android Device?

With the following code, it works with "ionic serve" (browser), when I click on the "Facebook share button", I obtain a "Facebook window pop-up" and I can share datas without any problems.
When I test on my Android Device, I click on the "Facebook Share button", nothing's happen ! And I obtain no error in the console with "chrome://inspect/#devices"
My "Facebook pop-up" is it blocked on device ?
Why is not displayed on device ?
Any ideas ?
In my Controller
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxMyIdxxx',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
(function() {
var e = document.createElement('script');
//e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.src="https://connect.facebook.net/en_US/all.js";
e.async = true;
document.getElementById('share_button').appendChild(e);
}());
$scope.shareFacebook = function(){
var titleShareFb = "myTitle1";
var imgShareFb = "http://www.example.com/img/1.jpg";
//e.preventDefault();
FB.ui({
method: 'feed',
name: titleShareFb,
link: 'http://www.example.com',
picture: imgShareFb,
caption: 'myCaption1',
description: 'myDescription1',
message: ''
});
}; //end of $scope.shareFacebook = function(){
In my View
<div id="cssShareFacebook">
<img ng-click="shareFacebook()" id="share_button" src="http://www.example.fr/img/facebookShare.png">
</div>
Thank you
here you are the best solution that I can found :
I used this source (Look carefully at what you can do and what you can not do)
https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin/blob/master/README.md
In Ionic Front, I call an url
$scope.urlFacebook = function(){
var urlFb = "http://www.troubadourstory.fr/App/fb_share/" + $scope.point._id;
window.plugins.socialsharing.share(null, null, null, urlFb);
};
in back I use Html meta like this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraphprotocol.org/schema/" class="">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="imagetoolbar" content="no">
<title>J'ai visité "<%= dataPoi.Poi.title %>" avec l'application mobile Troubadour Story !</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache,must-revalidate">
<meta http-equiv="expires" content="0">
<meta property="og:image" content="<%= dataPoi.Poi.picture %>" height="150px" width="150px">
<meta name="keywords" content="<%= dataPoi.Poi.title %>">
<meta name="description" content='Présenté par "<%= dataPoi.Poi.user.username %>" : <%= dataPoi.Poi.content %>'>
</head>
you can test you URL from HTML meta with this link
https://developers.facebook.com/tools/debug
Hope, this, can help ;-)

Is there a way to access a file within the www folder from another file inside the same www folder using phonegap?

I am trying to access a text file inside the www folder of one of my phonegap applications from the index.html. I don't think filereader works because it accesses the phone's file system and not the application's file system. Regardless, here's what I tried and it jumps to the error function when this line is called within gotFS:
fileSystem.root.getFile("version.txt", null, gotFileEntry, fail);
Here's my full index.html code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script charset="utf-8" src = "jquery-1.10.1.min.js"></script>
<script charset="utf-8" src = "cordova-2.7.0.js"></script>
<script>
function test()
{
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
document.write("gotFSreached");
fileSystem.root.getFile("version.txt", null, gotFileEntry, fail); // this jumps to fail
}
function gotFileEntry(fileEntry) {
document.write("gotFileEntryreached");
fileEntry.file(gotFile, fail);
}
function gotFile(file){
document.write("gotFilereached");
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
document.write(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
document.write("error");
}
</script>
<body>
<button type="button" onclick="test()">Print version.txt</button>
</body>
</html>
$.get("version.txt", function(data) {
// there u have version.txt data (in var data)
});

Localstorage my geolocation

I want to make an app which gets my coördinates and shows them in google maps (using phonegap and testing on emulator 2.2). Then stores those coördinates in localstorage. I have never used localstorage before so i am not sure on how to do this. I got the geolocation part working. If anyone could adjust my code or show a tutorial which explains how to save the lat/long that i will retreive as i don't have a lot of experience using web-langauges. It would be greatly appreciated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width; height=device-height; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Beer Me</title>
<link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript">
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
}
//GEOLOCATION
var onSuccess = function(position) {
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
//MAP
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLat, myLong),
map: map,
title:"Hello World!"
});
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError,{'enableHighAccuracy':true,'timeout':10000});
</script>
</head>
<body onload="onLoad()">
<div id="map_canvas" style="width:400px; height: 400px;">
</div>
</body>
</html>
I would suggest you use the SQLite Databases from Android.
You can then store the locations with two fields and access the data with SQL queries.
A nice tutorial is the one from Lars Vogel.
You could also use the Internal Storage from Android. Using a simple file is easy but not as powerful as the sql variant. When the data size increases reading and storing to the file becomes more cumbersome.

phoneGap database creation example

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.

Categories

Resources