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.
Related
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.
I'm using Phonegap Build to develop an application for iOS and Android.
I'd like to determine the locale (e.g. 'en-US') for the device, though I'd settle for the current language setting, or even the app store my app was installed from (it's been a long day).
Following the instructions here for the Globalization plugin I think I have everything right, but nothing seems to work on either the iPhone 6 or Samsung Galaxy Nexus I'm using for testing.
The relevant part of my config.xml looks like this:
<gap:plugin name="org.apache.cordova.globalization" />
My function for getting locale from the plugin looks like this:
var getPhoneGapLocaleName = function() {
var loc = 'unknown';
if (navigator.globalization !== undefined) {
navigator.globalization.getLocaleName(
function (locale) {
if (locale !== undefined) {
loc = locale.value;
}
},
function () {
// nothing
}
);
}
return loc;
};
Note: on both devices navigator.globalization.getLocaleName is present and appears correct, evaluating to a function resembling what I'd expect based on the documentation.
The problem here was that the variable 'loc' was declared outside the scope of the success or failure callbacks, which of course happen after a few brief moments.
I fixed this by changing the function thus:
var refreshPhoneGapLocaleName = function() {
if (navigator.globalization !== undefined) {
navigator.globalization.getLocaleName(
function (locale) {
if (locale !== undefined) {
localStorage['pg.locale'] = locale.value;
}
},
function () {
// nothing
}
);
}
};
Now calling it in onDeviceReady in order to refresh the values when the app starts.
A few moments later (not immediately) the following function can be used to retrieve the locale value:
var getLocale = function() {
return localStorage['pg.locale']();
};
The greatest thing about StackOverflow is how often it helps one to resolve one's own silly mistakes. :)
Although previous answers are returning the desired result, and giving an option to retrieve the current phonegap locale name, they did not explain the topic starter why his function did not work, and how to adjust his function to work in the way he intended (i.e. not using localStorage and not showing the locale in the console but giving the answer in real-time as a result)
I am posting this answer since I was looking for a quick function to get the device locale, and this post was my first result. While the opening post gave me everything I needed, I would like to answer this question for future visitors with the same purpose I had. Sorry for posting to a topic this old, but I hope I can help others with my answer.
The reason the function of topic starter does not work is the following: the plugin returns the locale in an asynchronous way. Therefore, the loc =locale.value line is only executed after the function's return statement. To fix this, we can write a wrapper function to simplify the plugins output as follows. Keep in mind that we need to use this function asynchronously, since the plugin result is also asynchronous.
The function:
var getPhoneGapLocaleName = function ( callback ) {
var unknownLocation = 'unknown'; //Default value
if ( navigator.globalization !== undefined ) {
navigator.globalization.getLocaleName(
function ( locale ) {
if ( locale !== undefined ) {
callback( locale.value );
} else {
callback( unknownLocation );
}
},
function () {
callback( unknownLocation );
}
);
} else {
callback( unknownLocation );
}
};
Use the function like this:
getPhoneGapLocaleName( function( loc ){ console.log( 'The locale was set as follows: ' + loc ); } );
Try this code
When the browser is set to the en_US locale, this should display a popup dialog with the text language: English:
navigator.globalization.getPreferredLanguage(
function (language) {alert('language: ' + language.value + '\n');},
function () {alert('Error getting language\n');}
);
Full Example
<!DOCTYPE HTML>
<html>
<head>
<title>getPreferredLanguage Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function checkLanguage() {
navigator.globalization.getPreferredLanguage(
function (language) {alert('language: ' + language.value + '\n');},
function () {alert('Error getting language\n');}
);
}
</script>
</head>
<body>
<button onclick="checkLanguage()">Click for language</button>
</body>
</html>
As I am having real troubles debugging an app in Android / iOs, can someone tell me some simple test to check if Cordova File API is loaded and works ?
Something like:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
if(fileAPI){ // what can I test there ?
alert('File API is OK');
}
}
Try to request the FileSystem
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
alert("it works");
}, function (e) {
alert("it doesn't work");
});
we are having a problem with the built in browser on Android 4.0, 4.1 and 4.2 (we haven't got anything lower to test on).
The problem is that the ajax call will work perfectly on first load, you can press the run Ajax button as many times as you like and it will be fine. You can disconnect from the internet and it will work properly.
But if you exit (FULLY, make sure its not just running in the background) the browser then relaunch it, it will fail on load and on button press. It doesn't matter if you are on-line or off-line.
The error that is been returned from the ajax call is "Error" with status = 0 and readyState = 0.
When its successful you get a message back says "respose from Ajax Call" with a status = 200 and a readyState = 4.
The code works find on every other browser we have tested on Android Chrome, Firefox and Opera. on IOS 5 and 6 it works and every desktop browser we can find.
Is there something that I missing or have we found a bug in the built in browser. Any help on this would be appreciate especially if it just something stupid I have done.
We have created a test script that demonstrates this problem well I have attached it to the bottom of this message.
Thanks
Tim
test.php
<?php
function displayPage() {
?>
<!DOCTYPE html>
<html manifest="test.manifest" debug="true">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" >
<title>test</title>
<script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">
function runAjaxGet() {
var XMLHttpRequest = $.ajax({
url: "test.php",
dataType: "json",
data: "test=test",
traditional: "true",
success: function( responseData ) {
alert('good\n responseData: '+responseData+ '\n res:' + XMLHttpRequest.responseText +'\n readyState: '+ XMLHttpRequest.readyState + '\n Status: '+XMLHttpRequest.status );
console.log(XMLHttpRequest);
},
error: function (xhr, ajaxOptions, thrownError, responseData) {
alert('bad\n responseData: '+responseData+ '\n res:' + XMLHttpRequest.responseText +'\n readyState: '+ XMLHttpRequest.readyState + '\n Status: '+XMLHttpRequest.status);
console.log(XMLHttpRequest);
}
});
}
$(document).ready(function() {
runAjaxGet();
});
</script>
</head>
<body>
<button Name="Run Ajax" onclick="runAjaxGet();">Run Ajax</button>
</body>
</html>
<?php
}
function processRequests() {
header("Content-Type: application/json; charset=UTF-8" );
echo (json_encode("respose from Ajax Call"));
}
date_default_timezone_set ( "UTC" );
if (isset($_REQUEST['test'])) {
$which = $_REQUEST['test'];
} else {
$which = '';
}
switch ($which) {
case "test":
processRequests();
break;
default :
displayPage();
break;
}
?>
test.manifest
CACHE MANIFEST
test.php
jquery-1.9.0.min.js
test.php?test=test
Just add NETWORK section with asterisk and it will work
CACHE MANIFEST
test.php
jquery-1.9.0.min.js
test.php?test=test
NETWORK:
*
I hit this same problem and determined that when retrieved from the cache, 0 indicates success. This is likely because there is no actual http request involved since the request is resolved entirely locally.
Appcache manifest file:
CACHE MANIFEST
CACHE:
/config
Javascript:
var request = new XMLHttpRequest();
request.open('GET', '/config', false); // async=false is ok because this file will always come from AppCache
request.send(null);
// Older versions of android return 0 when ajax request retrieved from appcache
if (request.status == 200 || request.status == 0) {
return JSON.parse(request.responseText);
} else {
console.log("ERROR: config not retrievable");
throw "Attempt to retrieve config return http status " + request.status;
}
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.