Phonegap in Android onDeviceReady function - javascript

I am using phonegap in android development. I wrote that PoC, however I can not figure out why it does not change the latitude of profile variable. Actually
alert(profile.latitude);
runs before the
geoCode.setLocation();
here is my code;
document.addEventListener("deviceready", onDeviceReady, false);
var profile = {
name: "",
id: "red",
latitude: "xx",
longtitude: "",
setCoordinates: function (latit, longt) {
this.latitude = latit;
this.longtitude = longt;
}
};
var geoCode = {
onSuccess: function (position) {
profile.latitude = position.coords.latitude;
},
onError: function (error) {
},
setLocation : function () {
navigator.geolocation.getCurrentPosition(this.onSuccess, this.onError);
}
};
// Wait for PhoneGap to load
//
function onDeviceReady() {
geoCode.setLocation();
//alert("2");
alert(profile.latitude);
};
thanks in advance

navigator.geolocation.getCurrentPosition is an asynchronous function. You need to do something like :
var geoCode = {
setLocation : function (callback) {
onSuccess: function (position) {
callback(position.coords.latitude);
},
onError: function (error) {
},
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
};
// Wait for PhoneGap to load
//
function onDeviceReady() {
geoCode.setLocation(function(latitude) {
alert(latitude);
});
};

Quite simply it is because the call to navigator.geolocation.getCurrentPosition() is an asynchronous call. Thereby the execution of the program continues and you see the alert. Sometime after the alert is show the onSuccess call of your geoCode class is called updating the profile.latitude value.

Related

Stub a Promise in PhantomJS/Sinon

I have a class in jquery that calls a service and returns a promise, which is then executed in my main area via a .done and Im trying to wrap that call in a another class I have that will make sure multiple calls are not made for the same ID. However I am finding this very very difficult to test as I can not accurcately get the promise working in phantomJS/Sinon. Heres what the area Im trying to test is
LOCKER.execute(diagRunId, function (unlock) {
SERVICE_ACCESSOR.makeCall params)
.done(function (data) {
console.log("Success!");
unlock();
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("Failed!");
unlock();
});
});
and In my test file I have my setup like so
var setup = function() {
P.mock('service-accessor', function () {
return {
makeCall: sinon.stub().returns({})
};
});
P.mock('locker', function () {
var methods = {
execute: function (lockId, wrapped) {
console.log('locked - ' + lockId)
wrapped()
},
unlock: sinon.stub()
};
return {
execute: methods.execute,
unlock: methods.unlock
};
});
P.start();
}
with finally the test just calling the method
aui.suite('Locker Test', function () {
aui.test('should lock and then unlock', testFile, {
setup: setup,
browser: function () {
P.when('utils', 'service-accessor','locker').execute(
'test', function (SERVICE_ACCESSOR, LOCKER) {
UTILS.makeCall("Identifier")
expect(LOCKER.unlock).to.have.been.called.once;
done();
}
);
},
validate: function () {},
});
});
The locker works and begins execution of the service call, but then the service call fails with
Error: PhantomJS: `TypeError: 'undefined' is not a function (evaluating 'SERVICE_ACCESSOR.callService( params).done')` near
L2492> }).fail(function (jqXHR, textStatus, errorThrown) {
From my understanding my mock should return a just a empty object when its being called, but then I dont understand a) Why its going to fail and b) Whats undefined? My assumption is that its because Im not returning three objects, but Im trying to get it to succeed first! How can I correctly stub/mock this?
In the end I didn't make a promise or use a stub. I used the following function that would call the done and fail in my call instead.
function() {
return { done: function(callback) {
if(window.makeParamountCallSuccess) {
callback({"data": "data"});
return {
fail: function(){}
}
} else {
return {
fail: function(failCallback){ failCallback("jqXHR", "textStatus", "errorThrown")}
}
}
}
}
}```

synchronous call weather api and then display the information

Purpose:
onClick event trigger synchronous call to getWeather() then call display()
var position={} // object containing latitude and longitude
var getWeather = function(pos) {
$.getJSON('https://api.openweathermap.org/data/2.5/weather', {
lat: pos.lat,
lon: pos.lng,
appid: "*****appid***"
}, showWeather, 'jsonp');
return new Promise(function (resolve, reject) {
resolve(weather_data)
});
};
var showWeather = function(data) {
return weather_data;
};
function display(weather_info){
console.log(weather_info);
}
These are the above two functions that I want to run synchronously using promise and in the respective order;
Problem:
When I used it in click function it does not not return the weather_data.
$("html").click(function() {
getWeather(position)
.display(getWeather);
});
What am I doing wrong?
showWeather callback function from $.getJSON is creating this trouble. I don't know where to return the promise();
I solved it myself
JsFiddle of the correction
var getWeather = function(pos) {
return new Promise(function (resolve, reject) {
var data_w={};
$.getJSON('https://api.openweathermap.org/data/2.5/weather', {
lat: pos.lat,
lon: pos.lng,
appid: "*****appid****"
}, function(data) { resolve(data)}, 'jsonp');
});
};
This above lines speaks for themselves. I have made the whole API call a promise. That's how I solved it.
If someone finds better way, please respond!

angularJS controllers functions callback

I am wondering how callbacks works in angularJS.
I have this code working perfectly like this
$scope.loginFB = function () {
hello(FACEBOOK).login(function () {
hello(FACEBOOK).api('me').then(function (profile) {
console.log('successful api call');
dbService.handle_credentials(profile);
$rootScope.$apply(function () {
$location.path('/homePage');
});
}, function(){
console.error('something went wrong with authentification');
});
});
};
but works in weird way when refactored like this
$scope.loginHandler =function () {
hello(FACEBOOK).api('me').then(function (profile) {
console.log('successful api call');
dbService.handle_credentials(profile);
$rootScope.$apply(function () {
$location.path('/homePage');
});
}, function(){
console.error('something went wrong with authentification');
});
};
$scope.loginFB = function () {
hello(FACEBOOK).login($scope.loginHandler());
};
please tell me what i am doing wrong with this refactoring.
By including the params, you are immediately invoking your function callback rather than passing a function reference, which is what you really want to do.
$scope.loginFB = function () {
hello(FACEBOOK).login($scope.loginHandler);
};
If you want to pass a parameter to your callback function, you can use one of two approaches.
Wrap your callback in an anonymous function
$scope.loginFB = function () {
hello(FACEBOOK).login(function() { return $scope.loginHandler(param); });
};
In a modern browser, use .bind().
$scope.loginFB = function () {
hello(FACEBOOK).login($scope.loginHandler.bind(this, param)));
};

how to access javascript function

I have this code for websocket. I want to call function broadcast for lRes. how can I do this?
var lRes = jwsc.logon('ws://localhost/WS', 'sendToWS', 'root', {
// OnOpen callback
OnOpen: function(aEvent) {
},
// broadcast callback
broadcast: function() {
var lRes = jwsc.broadcastText(
"",
lMsg // broadcast this message
);
},
// OnMessage callback
OnMessage: function(aEvent, aToken) {
},
// OnClose callback
OnClose: function(aEvent) {
},
});
Well, Here I suggest you to call your function like :-
lRes.broadcast();

FileReader & FileWriter issues (cordova 2.0.0 js)

I've been working on this bit of PhoneGap (cordova-2.0.0.js) code for an Android* device to persist some data. I'm getting this weird error code and the file doesn't seem to be getting written. I started with the example code and could write an inline string to a file handle successfully, so I'm sure my permissions and all are correct.
Perhaps I'm not handling all the callbacks correctly? There are a lot to listen for! It could be something with truncate(0); I had a hard time finding much documentation on it. Do I need to call window.requestFileSystem more than once? I do it 2x to register different callbacks. If not this, what is causing the error?
Suggestions on reducing the total number of lines for a Read + Write operation will be gladly accepted as well...
*Emulator running Android 2.3.4
here's my code:
var CREDENTIALS_FILE_NAME = "credentials.json";
var credentials;
// INIT -- Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, initCredentialReader, fail);
}
function initCredentialReader(fileSystem) {
fileSystem.root.getFile(CREDENTIALS_FILE_NAME, {create: true}, gotFileEntryReader, fail);
}
function gotFileEntryReader(fileEntry) {
fileEntry.file(gotFileToRead, fail);
}
function gotFileToRead(file){
var reader = new FileReader();
reader.onloadend = function(e) {
console.log("--FILE READER: "+e.target.result);
if( e.target.result.length < 1 ) {
credentials = newCredentials();
} else {
credentials = JSON.parse( e.target.result );
}
};
reader.readAsText(file);
}
// END CHAIN
function initCredentialWriter(fileSystem) {
fileSystem.root.getFile(CREDENTIALS_FILE_NAME, {create: true}, gotFileEntryWriter, fail);
}
function gotFileEntryWriter(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwrite = function(e) {
console.log("--- write success");
};
var toWrite = JSON.stringify(credentials);
console.log("--- toWrite: "+toWrite);
writer.truncate(0);
writer.seek(0);
writer.write(toWrite);
}
function fail(error) {
console.log("--- write FAIL: "+error.code);
}
function newCredentials() {
console.log("returning newCredentials!");
return {
"username" : "",
"password" : "",
"organization" : "",
"cookieValue" : "" };
}
function getCredentials() {
console.log("--- getCredentials: "+credentials);
return credentials;
}
function saveCredentials( jsonCredentials ) {
console.log('--- saveCredentials jsonCredentials: '+ jsonCredentials);
credentials = JSON.stringify( jsonCredentials );
console.log('--- credentials to save: '+credentials)
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, initCredentialWriter, fail);
return credentials;
}
ERROR
08-14 18:41:38.839: I/Web Console(2678): Error in success callback:
File9 =
{"code":7,"line":2863,"expressionBeginOffset":91407,"expressionEndOffset":91455,"sourceId":4122528,"sourceURL":"file:///android_asset/www/cordova-2.0.0.js"}
at file:///android_asset/www/cordova-2.0.0.js:258
So, turns out that calling truncate() and write() is not asynchronously correct-- just had implement more callbacks, like so:
function initCredentialTruncate(fileSystem) {
fileSystem.root.getFile(CREDENTIALS_FILE_NAME, {create: true}, gotFileEntryTruncate, fail);
}
function gotFileEntryTruncate(fileEntry) {
fileEntry.createWriter(gotFileTruncate, fail);
}
function gotFileTruncate(writer) {
writer.onwrite = function(e) {
console.log("--- truncate success");
};
writer.truncate(0);
//writer.seek(0);
}
// END CHAIN
and call the init function when necessary. thx for letting me vent, StackOverflow...

Categories

Resources