PhoneGap on Android deviceready not working! - android

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.

Related

Websockets in WebViews failing to connect, returning code 1006

I have created a simple websocket in an HTML page that works great and connects fine in all of the web browsers. However, when I load it in a web view like in an Android App it fails to connect and returns the code 1006. It is trying to connect to a different URL/endpoint so I am thinking this might be a CORS issue. I am building for a minimum target of API 23.
<!DOCTYPE html>
<html>
<body>
<h1>Socket Connect</h1>
<div id="container"></div>
</body>
<script>
const div = document.getElementById('container');
try {
console.log('connect');
var ws = new WebSocket('wss://anotherserver.com:3000');
ws.binaryType = 'arraybuffer';
}
catch (err) {
}
ws.onerror = function (error) {
// error is always blank
console.log('error');
};
ws.onopen = function () {
div.textContent = 'Opened';
console.log('opened');
};
ws.onclose = function (error) {
// always = 1006
div.textContent = error.code;
console.log(error.code);
};
</script>
</html>
I have read a few other posts about setting some options in my code and I have done that. See here
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.getSettings().setDatabaseEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setCacheMode(currentCacheMode); /* use cache if not expired */
myWebView.getSettings().setJavaScriptEnabled(true);
I have set cleartext in my manifest as well
It ended up being a CORS issue.

navigator.contacts is undefined

I want to view all contacts but the navigator.contacts is undefined.
cordova plugin add cordova-plugin-contacts
cordova build android
$(document).ready(function(){
$(document).on('deviceready', function(){
alert('something');
}, false); //it doesn't even alert something;
console.log(navigator.contacts);
});
I have take it out of document ready either. NO RESULT :(
Someone said the problem can be fixed by removing and adding platform android and adding plugin again, however it didn't!
I have also put the script tag to the end, in order that the page to be loaded then run the scripts.
I tried this code sometime back in my project and it worked:
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
$('#contact').click( function()
{
try {
var contact = navigator.contacts.create({"displayName": "CordovaUser"});
var phoneNumbers = [];
phoneNumbers[0] = new ContactField('work', '212-555-1234', false);
phoneNumbers[1] = new ContactField('mobile', '917-555-5432', true); // preferred number
phoneNumbers[2] = new ContactField('home', '203-555-7890', false);
contact.phoneNumbers = phoneNumbers;
contact.save();
alert("Contact created successfully");
}
catch(err) {
alert("Plugin Error - " + err.message);
}
});
}

XDK built app not working

I searched a lot, but I couldn't find an answer. I use Intel XDK for Cordova/Phonegap development.
Everything is ok (emulate tabs, debug, etc.). I went to Build tab and get my .apk, moved it to SD card and installed, but, it doesn't work when run.
If I build my source with Phonegap Build (Online), everything works fine.
My JS code:
<script type="text/javascript">
document.addEventListener("backbutton", function(){ return; }, true);
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
//navigator.splashscreen.hide();
var server = 'http://xxxxxx/index.php?';
var user_uuid = device.uuid;
$( document ).ready
(
function()
{
$("#main_content").css("top", "50%");
$("#main_content").css("margin-top", "-"+($("#main_content").height()/2)+"px");
$("#main_content").show();
$("#big_img_load").attr("src", "img/ajax-loader.gif");
var xinv = setInterval
(
function()
{
var networkState = navigator.connection.type;
if(networkState.trim() == 'none')
$("#no_internet").show();
else
{
$.post
(
server+"do=boot",{useruuid: user_uuid},function(data)
{
if(data.trim() != "ok")
window.location = "error.html";
else
{
clearInterval(xinv);
window.location = "app.html";
}
}
);
}
},
1000
);
}
);
};
</script>
It remains in loading: No internet check, no POST to the URL, nothing.
Where is the problem? Why only build from XDK is not working?
My suspicion is you do not have the domain whitelisting section in the build settings set correctly for your app. See this article for some hints: https://software.intel.com/en-us/articles/cordova-cli-412-domain-whitelisting-with-intel-xdk-for-ajax-and-launching-external-apps and make sure to build your app using Crosswalk, not Android, for best results on Android devices.

onDeviceReady not getting loaded

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.

Ajax inserts works with browsers but not with phonegap emulator (android)

I am developing an app with phonegap(cordova) version 3.2 and I am having problems with mysql insertion. The following codes works well in browsers (mobile or not) but, when I run the app with an android emulator or in a real device it doesn't work.
The scripts:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0-rc.1/jquery.mobile-1.4.0-rc.1.min.js"></script>
<script type="text/javascript">
app.initialize();
</script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#formCadastro").submit(function(){
var campoNome = new String(document.getElementById("txtNome").value);
var campoEmail = new String(document.getElementById("txtEmail").value);
var campoUsuario = new String(document.getElementById("txtUsuario").value);
var campoSenha = new String(document.getElementById("txtSenha").value);
var campoSenhaConf = new String(document.getElementById("txtSenhaConf").value);
$.ajax({
type: "POST",
url: "http://imagect.co.nf/cadastra.php",
crossDomain: true,
data: { nome: campoNome , email: campoEmail, usuario: campoUsuario, senha: campoSenha}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
window.location="index.html";
})
.fail(function(jqXHR, msg) {
alert( "Errooo:" + msg );
alert( "Errooo:" + jqXHR );
console.log("Erro chato:" + msg);
console.log(jqXHR + " " + msg);
});
});
});
</script>
The problem is that neither the fail function nor the success function happens. It seems that android ignores the ajax...
I have already tried using deviceready, pageinit, mobileinit etc. But nothing works well.
The manifest has the internet permission and the config.xml has the access origin = *.
Could someone please help me?
Thanks, sorry about my English.

Categories

Resources