navigator.contacts is undefined - android

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);
}
});
}

Related

Why doesn't the cordova-plugin-background-mode plugin work on android?

I'm trying to send the geolocation by ajax in intervals of 30 seconds in the background, since this application is being used to know the "real time" location of the deliverers at all times. The problem is that when you enable the plugin in the android version when generating the apk and installing it on the cell phone it doesn't work, even when you put the application in the background and put it back in the foreground it restarts completely.
These are the versions that I am using for the development of the application:
Cordova 10
Nodejs 14.16
JQuery 3.5
Structure:
js
login.js
home.js
index.html -- this is the login page where the login.js file is located
home.html -- this is the home page where the home.js file is located
login.js
document.addEventListener('deviceready', function () {
cordova.plugins.backgroundMode.enable();
});
home.js
let isSending = false;
let intervalId = null;
let email = window.localStorage.getItem("user_email");
let token = window.localStorage.getItem("token");
let path = window.localStorage.getItem("api_url");
let onMapSuccess = function (position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
if (!isSending) {
$.ajax({
type: "GET",
url: path + "/geoTransportista/" + email + "/" + latitude + "/" + longitude,
headers: {
Authorization: "Bearer " + token,
"Content-type": "application/json",
},
beforeSend: function() {
isSending = true;
}
}).done((res) => {
if (res.state == "successful") console.log("ENVIO EXITOSO");
}).fail((err) => {
console.log(err);
}).always(() => {
isSending = false;
});
}
};
let onMapError = function (error) {
isSending = false;
}
let getLocation = () => {
navigator.geolocation.getCurrentPosition(onMapSuccess, onMapError, {
enableHighAccuracy: true,
});
return getLocation;
}
document.addEventListener('deviceready', function (e) {
intervalId = setInterval(getLocation(), 30000);
cordova.plugins.backgroundMode.on('activate', function (e) {
cordova.plugins.backgroundMode.disableWebViewOptimizations();
if (intervalId) clearInterval(intervalId);
intervalId = setInterval(getLocation(), 30000);
});
cordova.plugins.backgroundMode.on('deactivate', function (e) {
if (intervalId) clearInterval(intervalId);
intervalId = setInterval(getLocation(), 30000);
});
});
#justin is wrong it works on Cordova 10+ but it does not support GPS however you can recall GPS function when you resume to app. I'm on Cordova 11.0.0 and its working fine. Also you can take a look a cordova-plugin-advanced-background-mode
cordova-plugin-background-mode does not work on Cordova 10. You can try downgrade to Cordova 9. The repo seems inactive for a while now, not sure if the author will ever fix it.

Cordova Contacts Plugin not always showing Contact List

I have the contacts plugin in my app and on one test device (iPhone 5, iOS 9.02) the contact list does not show. And when I do a search, nothing appears. I get no error messages. On some of my other devices like some Android or iOS 8.x devices it does work. This particular problem device has 1200 contacts. Anyone have some suggestions on how to fix? I'll paste the relevant part of my code. Although maybe it is more of a configuration issue?
$scope.getAllContacts = function(searchQuery) {
try {
var opts = { //search options
filter: searchQuery, // 'Bob'
multiple: true, // Yes, return any contact that matches criteria
fields: ['displayName', 'name']
};
if (ionic.Platform.isAndroid()) {
opts.hasPhoneNumber = true; //hasPhoneNumber only works for android.
};
$ionicLoading.show();
$cordovaContacts.find(opts).then(function(contactsFound) {
$scope.contacts = contactsFound;
$ionicLoading.hide();
});
} catch (err) {
alert(err.message);
}
};
$scope.getAllContacts("Ak");
Hi use this to save all contacts in sdcard and display. (default Cordova contacts and file plugin)
document.addEventListener("deviceReady", deviceReady, false);
function deviceReady() {
navigator.contacts.find(["*"], function(contacts) {
// alert("contacts.length = " + contacts.length);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile("contacts.json", {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwriteend = function(){
// Success Contacts saved to sdcard as a contacts.json file
// Now get and read the json file
var path = fileSystem.root.getFile("contacts.json", {create:false},gotFileEntry, fail);
// jquery
$.getJSON(path, function (data) {
user = data;
$.each(user, function (index, user) {
var all_item = '<p id="'+user.id+'">'+user.displayName+'</p>';
$('#allcontacts').append(all_item);
});
});
};
writer.write(JSON.stringify(contacts));
}, onError);
}, onError);
}, onError);
}, onError,{"multiple": true});}
function onError(){
alert("Error");
}
You may use navigator.contacts.find, and see if this works in your phone.
For more details
https://github.com/apache/cordova-plugin-contacts

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.

Phonegap Contact plugin is not working for me on Android. I am using phonegap build

Contact plugin is not working for me on Android. I am using phonegap build
I have added this in config.xml
<gap:plugin name="org.apache.cordova.contacts" />
Here is my code :
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
// specify contact search criteria
var options = new ContactFindOptions();
options.filter=""; // empty search string returns all contacts
options.multiple=true; // return multiple results
filter = ["displayName"]; // return contact.displayName field
navigator.contacts.find(filter, onSuccess, onError, options);
}
// onSuccess: Get a snapshot of the current contacts
function onSuccess(contacts) {
for (var i=0; i<contacts.length; i++) {
alert(contacts[i].displayName);
}
};
// onError: Failed to get the contacts
function onError(contactError) {
alert('onError!');
}
Can any one help me what can be the reason?
I also need the fetch the contacts of a particular group. I couldn't anywhere in the documentation. Is it supported in any of the available contact plugins?
Try adding scope to the callbacks: onSuccess and onError in your contact function call. Use your app's main scope app or whatever you set it.
navigator.contacts.find(filter, app.onSuccess, app.onError, options);

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