Not able to get error in pubnub javascript callback - javascript

I am following the howto in this blog post: http://www.pubnub.com/blog/sending-android-push-notifications-via-gcm-javascript-using-phonegap/
Up til now I have done the following:
Created a new project in Google Dev Console
Turned on Google Cloud Messaging for Android
Got the sender ID (project number) and a server
key
Then added push plugin to existing project:
$ cordova plugin add https://github.com/phonegap-build/PushPlugin.git
Then copied PushNotification.js from the plugin to my js lib folder.
I am loading both this js file and the pubnub cdn with requirejs, which seems to work fine.
I created a module with the scripts from 2.2 in the howto.
define(['env-config','datastore/localstore','jquery','push','pubnub'],function (EnvConfig,Store) {
var pushNotification = window.plugins.pushNotification;
function register() {
pushNotification.register(
successHandler,
errorHandler,
{ 'senderID':EnvConfig.push.senderid, 'ecb':'onNotificationGCM'}
);
}
function successHandler(result) {
console.log('Success: '+ result);
}
function errorHandler(error) {
//** The following line throws:
//** java.lang.Long cannot be cast to java.lang.String
console.log('Error:' + error);
}
function onNotificationGCM(e) {
switch(e.event){
case 'registered':
console.log("Device registered with id "+e.regid);
Store.set("pushid"+e.regid);
/*if (e.regid.length > 0) {
deviceRegistered(e.regid);
} */
break;
case 'message':
if (e.foreground){
//What needs to be done when app is in the foreground
//while receiving a notification
console.log('A notification has been received');
}
break;
case 'error':
console.log('Error: ' + e.msg);
break;
default: console.log('An unknown event was received');
break;
}
}
var module = {
init: function() {
register();
}
};
return module;
});
When device is ready, I call the init function of this module.
At the moment register() fails and executes the errorHandler callback. But console.log fails with: java.lang.Long cannot be cast to java.lang.String. Therefore I have no idea what to do next...
Any pointers is much appreciated.
Samsung Galaxy S5
Android 4.4.2
Chrome 30.0 (in webview)
Cordova 3.6.3-0.2.13

Ah, I think I know what's going on-
Your sender ID has to be in string! You are probably using it as a number.
BTW, thanks for trying out the tutorial I wrote :-)

Related

Cordova Camera access crash app on Nexus 7 with Android 6.0.1

Using Cordova 6.3.1, I installed the following Crodova plugins:
cordova-plugin-camera, cordova.plugins.diagnostic, phonegap-plugin-barcodescanner
I'm using the following JavaScript code to access the Camera and scan a QR code:
function scanQR() {
cordova.plugins.diagnostic.requestCameraAuthorization(function(status) {
console.log("Authorization request for camera returned " + status);
if (status == cordova.plugins.diagnostic.permissionStatus.GRANTED) {
try {
cordova.plugins.barcodeScanner.scan(scanQRDone, function (error) {
console.log(error);
});
} catch (e) {
console.log(e.message);
}
}
}, function (error) {
console.log(error);
});
}
function scanQRDone(result) {
console.log(result);
}
The requestCameraAuthorization call prompts for a confirmation on the device and when allowed returns status GRANTED.
However the call to cordova.plugins.barcodeScanner.scan simply crashes the application on the Nexus 7.
The actual line in which the crash occurs is cordova.js line 940:
var msgs = nativeApiProvider.get().exec(bridgeSecret, service, action, callbackId, argsJson);
Where service="BarcodeScanner" and action="scan"
Seems like some kind of version mismatch in native code, any ideas are welcomed.
Creating a new ionic application from scratch and copying the content of the www folder into it has resolved the problem.
in the file config.xml add this
< platform name="android" > <br>
< preference name="android-targetSdkVersion" value="23" /> <br>
< /platform>

Update UI when Service Worker installed successfully

Looks like Service Worker runs in a worker context and has no access to the DOM. However, once Service Worker installed, I want my users to know that the app will now work offline. How can I do that?
When the Service Worker is in activated state, this is the perfect time to display the toast 'Content is cached for offline use'. Try something below code while registering your service worker.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js').then(function(reg) {
// updatefound is fired if service-worker.js changes.
reg.onupdatefound = function() {
var installingWorker = reg.installing;
installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and the fresh content will
// have been added to the cache.
// It's the perfect time to display a "New content is available; please refresh."
// message in the page's interface.
console.log('New or updated content is available.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a "Content is cached for offline use." message.
console.log('Content is now available offline!');
}
break;
case 'redundant':
console.error('The installing service worker became redundant.');
break;
}
};
};
}).catch(function(e) {
console.error('Error during service worker registration:', e);
});
}
After testing #Prototype Chain's answer above, I wanted to use named functions as opposed to nested anonymous functions as event handlers to make code more pleasant to look at for my taste, and hopefully easier to understand later/for others.
But only after spending some time sorting docs, I managed to listen correct events on correct objects. So sharing my working example here in hopes of saving someone else from tedious process.
// make sure that Service Workers are supported.
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/sw.js')
.then(function (registration) {
console.log("ServiceWorker registered");
// updatefound event is fired if sw.js changed
registration.onupdatefound = swUpdated;
}).catch(function (e) {
console.log("Failed to register ServiceWorker", e);
})
}
function swUpdated(e) {
console.log('swUpdated');
// get the SW which being installed
var sw = e.target.installing;
// listen for installation stage changes
sw.onstatechange = swInstallationStateChanged;
}
function swInstallationStateChanged(e) {
// get the SW which being installed
var sw = e.target;
console.log('swInstallationStateChanged: ' + sw.state);
if (sw.state == 'installed') {
// is any sw already installed? This function will run 'before' 'SW's activate' handler, so we are checking for any previous sw, not this one.
if (navigator.serviceWorker.controller) {
console.log('Content has updated!');
} else {
console.log('Content is now available offline!');
}
}
if (sw.state == 'activated') {
// new|updated SW is now activated.
console.log('SW is activated!');
}
}

Trouble setting up facebook login

I am building a hybrid mobile app based out of JavaScript, CSS and HTML. I am using the Intel XDK to develop and deploy the app.
For Facebook integration I am using the following third party plugin to work it out.
My aim is to get it to work both on iOS and Android. I have done the followings:
<button onclick="fblogin()"> Login </button>
Script:
<script>
function fblogin() {
var fbLoginSuccess = function (userData) {
alert("UserInfo: " + JSON.stringify(userData));
}
facebookConnectPlugin.login(Array strings of permissions, Function success, Function failure);
facebookConnectPlugin.login(["public_profile"],
fbLoginSuccess,
function (error) { alert("" + error) }
);
}
</script>
The issues:
I have already enabled the plugin with my javascript api on the intel xdk.
fblogin() not defined at the following line:
facebookConnectPlugin.login(Array strings of permissions, Function success, Function failure);
I have read through the guide but is still confused. I would appreciate if someone could give me a step by step guide on making this work.
I would suggest to look at the sample code on the README (https://github.com/Wizcorp/phonegap-facebook-plugin#sample-code)
You can write your function like this:
function fblogin() {
var fbLoginSuccess = function (userData) {
alert("UserInfo: " + JSON.stringify(userData));
}
facebookConnectPlugin.login(["public_profile"],
fbLoginSuccess,
function (error) { alert("" + error) }
);
}
i.e remove the
facebookConnectPlugin.login(Array strings of permissions, Function success, Function failure)
line.

Cannot record audio with Cordova Media plugin on Windows (Phone) 8.1

I'm trying to create an app that allows the user to record audio. I'm using the cordova-plugin-media for this.
Using the sample from the documentation I can record sound on iOS (specifying a *.wav file), Android (*.amr), Windows Phone 8 (*.aac), but Windows Phone 8.1 doesn't work. I've tried it with *.mp3, *.wma, and *.m4a, but in every case I get this error:
No suitable transform was found to encode or decode the content.
Here's part of the code:
var that = this;
try {
this._media = new Media('recording.mp3', function () {
that._log('Audio success');
}, function (e) {
that._log('Error: ' + e.code + ': ' + e.message);
});
// Bind buttons
document.querySelector('#recordStart').addEventListener('click', function () {
// Record
that._log('Recording...');
that._media.startRecord();
});
document.querySelector('#recordStop').addEventListener('click', function () {
that._log('Recording stopped');
that._media.stopRecord();
});
}
catch (e) {
this._log('An error occurred!');
this._log(e.message);
}

Apache cordova - unable to write to file in android

I am trying to create a file in the PERSISTENT (sd card) storage using cordova's api in javascript. I am able to create the file, but unable to write data to it (data is empty on read). Below is my JS code:
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
writeTestList();
}
function writeTestList() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystemForWrite, function() { showMsg('Unable to access file system for write'); });
}
function gotFileSystemForWrite(fileSystem) {
fileSystem.root.getFile('testList.txt', {create: true, exclusive: false}, gotFileEntryForWrite, function() { showMsg('Unable to access file for write'); });
}
function gotFileEntryForWrite(fileEntry) {
fileEntry.createWriter(gotFileWriter, function() { showMsg('Unable to create test list'); });
}
function gotFileWriter(writer) {
writer.onwrite = function(evt) {
// show a message
alert('created the test lists');
readSavedContent();
};
writer.onerror = function(evt) {
alert(JSON.stringify(evt));
};
writer.write("raj");
alert(writer.length);
}
The control always goes inside onerror of writer and on alerting the event obj, i see a type: "error", error: "JSON error". I completely don't get this. I am writing to a txt file, but getting json error. I have put write permissions in android manifest. Also, I have storage plugin for cordova enabled in config.xml preferences. People, pls help me out with this..!!
Unable to fix this issue in cordova 3.0. Moved to cordova 2.9 and everything works perfectly.

Categories

Resources