How can I get device Locale or Language with PhoneGap Build? - android

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>

Related

Why *ngIF is not working in Cordova Angular?

I have been stucked in this for a while. It is confirm that this.progressBarValue is changed to true. But the progress bar is not displaying. Can someone help me with this thanks in advance.
some-component.html
<div class="progressBar">
<mat-progress-bar class="fileProgress" mode="indeterminate" *ngIf="progressBarValue">
</mat-progress-bar>
</div>
some-component.ts
confirmConversion() {
this.progressBarValue = true;
console.log(this.progressBarValue)
var filepath = this.filePath;
var fileextension = this.settingsExtension;
new Promise((resolve, reject) => {
window.ConvertMedia(filepath, fileextension, resolve, reject);
}).then((message) => {
console.log(message);
});}
It is working(Progress bar is displayed) if I don't call that Cordova API. I also tried this using some methods given below but it didn't worked.
this.zone.run(() => this.progressBarValue = true)
console.log(this.progressBarValue)
this.changeDetector.detectChanges() & this.changeDetector.markForCheck()
Note: ProgressBar is displayed if I update this.progressBar = true inside
.then((message) => {console.log(message);});
I would try to add *ngIf to container - div like that:
<div class="progressBar" *ngIf="progressBarValue">
<mat-progress-bar class="fileProgress" mode="indeterminate">
</mat-progress-bar>
</div>
If default value for progressBarValue is false mat-progress-bar could not load properly.
Write if it helps or still nothing ;)
Also you can add to your html code
eg. :
<span> {{progressBarValue}} </span>
to keep track of value and be sure if it's even changing

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.

Android InAppBrowser virtual keyboard closes on executeScript(). [phonegap]

I copied my code from the following link. It's a workaround for Passing Data From an InAppBrowser back to the app.
blogs.telerik.com/appbuilder/posts/13-12-23/cross-window-communication-with-cordova's-inappbrowser
The problem is that after each executescript() the Keyboard disappears.
This issue status here is "won't fix". So I'm wondering if there is an alternative solution. I only see a reference to KitKat users, but that would only represent a limited amount.
https://issues.apache.org/jira/browse/CB-5449
Suggestions?
setName: function() {
var win = window.open( "http://jsfiddle.net/tj_vantoll/K2yqc/show", "_blank",
"EnableViewPortScale=yes" );
win.addEventListener( "loadstop", function() {
win.executeScript({ code: "localStorage.setItem( 'name', '' );" });
var loop = setInterval(function() {
win.executeScript(
{
code: "localStorage.getItem( 'name' )"
},
function( values ) {
var name = values[ 0 ];
if ( name ) {
clearInterval( loop );
win.close();
$( "h1" ).html( "Welcome " + name + "!" );
}
}
);
});
});
}
Depending on your use case, it might be a feasible workaround to check if the keyboard is currently visible and avoid calling executeScript in that case.
Try using the com.ionic.keyboard plugin to get cordova.plugins.Keyboard.isVisible and use that in your setInterval function.

Calling an External Javascript Function

I have an app i'm programming in Javascript/JQuery. I'm using PhoneGap and want to use localStorage to store the users credentials the first time they open the app and then autofill next time the user opens the app. I want to call the checkPreAuth() right when the page loads. But It's not calling my function. Can anybody help me?
Calling the function from login.html:
<script>
$(document).ready(function() {
checkPreAuth();
});
</script>
And the function in my digest_auth.js:
function checkPreAuth() {
var form = $("#loginForm");
var values = new Array();
var username = $('#username').val();
var password = $('#password').val();
if(window.localStorage["username"] == undefined && window.localStorage["password"] == undefined) {
localStorage.setItem("username", username);
localStorage.setItem("password", password);
alert('Saved username and password');
} else {
alert(username + ', ' + password);
}
}
Maybe this is the answer to your problem. I faced this problem and instead of using document ready of jquery, i used this:
JQuery document.ready vs Phonegap deviceready

PhoneGap on Android deviceready not working!

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.

Categories

Resources