can not remove contacts, android phonegap - android

I am working on android application in phonegap-3.1.0
I want to use phone contacts in my application, So I have refer this Document.
Successfully installed the plugins for contacts
When I remove saved contact(save from javascript code), It alerts Removal Success
But when I go into the contacts, it is still not removed from here,
Every time I try, it saves the contact but not not removed since alerts like Removal Success,
What should I Do...
SO I need help on it, Why the contact can't be remove

I have created an app for contacts insert and delete
You can fork on github-> xxbinxx/phoneGap-ContactsApp-Android. you can definitely solve your issue after it.
I have used contact ID's for the deletion purpose.
Here's the short code...
var app ={
/********************SOME OTHER CODE*************************/
openContacts: function() {
app.initialize();
var options = new ContactFindOptions();
options.filter = "";
options.multiple = true;
var fields = ["*"]; //"*" will return all contact fields
navigator.contacts.find(fields, app.onSuccess, app.onError, options);
},
// Write contacts in DOM
onSuccess: function(contacts) {
var li = '';
$.each(contacts, function(key, value) {
if (value.name) {
$.each(value.name, function(key, value) {
if (key === 'formatted') {
name = value;
}
});
}
if (value.note) {
note = value.note;
}
if (value.id) {
id = value.id;
}
console.log("id : " + id + "-> name : " + name + " -> note : " + note);
li += '<li style="text-decoration:none;"><b>Name</b>: ' + name + '<div class="removeIcon pullRight" onclick="app.removeThisContact(\'' + id + '\',\'' + name + '\')"> </div><br><b> Note:</b> ' + note + '</li>';
}); // NOTICE the ID is passed as PARAMETER to remove specific contact.
$("#contact").html(li);
},
onError: function(contactError) {
alert('onError!' + contactError.code);
},
removeThisContact: function(id, name) {
console.log("removing contact : " + name);
options = new ContactFindOptions(); // find the contact to delete
options.filter.id = id;
options.multiple = "true";
var fields = ["displayName", "name"]; // you can take any..
navigator.contacts.find(fields, deleteThis, app.onError, options);
function deleteThis(contacts) {
var contact = contacts.pop();
// logging things to troubleshoot.
console.log('inside deleteThisContact: parameter passed: '+ contacts);
console.log("popped out:" +contact);
contact.remove(function() {
$('#status-area')
.flash_message({
text: 'Contact Removed!',
how: 'append'
});
app.openContacts();
}, null);
},
deleteAllTheContacts: function() {
var deleteContact = function(contacts) {
console.log("length = " + contacts.length);
// No contacts left, stop saving
if (contacts.length == 0) {
console.log("All contacts removed");
return;
}
var contact = contacts.pop();
contact.remove(function() {
deleteContact(contacts);
}, null);
};
navigator.contacts.find(["*"], deleteContact, app.onError, {
"multiple": true
});
},
/********************SOME OTHER CODE*************************/
}
$.fn.flash_message = function(options) {
//flash your message
}
Hope this will help you. :)

Related

PhoneGap : Fetch Contact list with optimize speed

In Phonegap I try to fetch the contact list from phone.I need just name and phone number , its taking around 40 seconds to fetch all the result.I add the plugin in config.xml .In my phone I have around only 400 contacts. But when I alert the length of contact in index.html it says that 1351 list.I don't know where I am wrong.I think some optimization is needed while fetching name and number from phone.
advance Thanks...:)
Config.xml
<feature name="Contacts">
<param name="android-package" value="org.apache.cordova.contacts.ContactManager" />
</feature>
index.html
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter="";
options.multiple=true;
filter = ["displayName", "phoneNumbers"];
navigator.contacts.find(filter, onSuccess, onError, options);
}
var cSort = function(a, b) {
aName = a.displayName ;
bName = b.displayName ;
return aName < bName ? -1 : (aName == bName ? 0 : 1);
};
function onSuccess(contacts) {
contacts = contacts.sort(cSort);
alert("length " + contacts.length );
var i =0;
for (var i = 0; i < contacts.length; i++)
{
console.log("Display Name = " + contacts[i].displayName);
if(contacts[i].displayName != null)
{
if( contacts[i].phoneNumbers == null )
continue;
else if(contacts[i].phoneNumbers.length)
{
for (var j=0; j<contacts[i].phoneNumbers.length; j++)
{
$('#contact_list').append('<li> Name:'+contacts[i].displayName+'</li>');
$('#contact_list').append('<li> Number:'+contacts[i].phoneNumbers[j].value+'</li><br><br>');
}
$('#contact_list').listview('refresh');
}
}
}
}
function onError(contactError) {
alert('onError!');
}
</script>
Change your code from:
{
for (var j=0; j<contacts[i].phoneNumbers.length; j++)
{
$('#contact_list').append('<li> Name:'+contacts[i].displayName+'</li>');
$('#contact_list').append('<li> Number:'+contacts[i].phoneNumbers[j].value+'</li><br><br>');
}
$('#contact_list').listview('refresh');
}
To:
{
var finalList = '';
listEntryPoint = $('#contact_list');
for (var j=0; j<contacts[i].phoneNumbers.length; j++)
{
finalList += '<li> Name:'+contacts[i].displayName+'</li>' + '<li> Number:'+contacts[i].phoneNumbers[j].value+'</li><br><br>';
}
listEntryPoint.append(finalList);
listEntryPoint.listview('refresh');
}
#BINIL S, you have a very expensive Jquery call:
$('#contact_list').append(...);
Change to:
listEntryPoint = $('#contact_list');
move that outside of the loop and assign it to a variable, that should help. You can also NOT insert the new entries one at at time. You CAN make the one large list before you insert into HTML. Like this,
finalList += '<li> Name:'+contacts[i].displayName+'</li>' + '<li> Number:'+contacts[i].phoneNumbers[j].value+'</li><br><br>';
After loop is done,
listEntryPoint.append(finalList);
That should help - Jesse

Android: How to passing a variable to the Parse.com cloud code

I am now working on CloudCode, and would like to retrieve the number of items in the Parse Database that is greater than certain criteria (i.e. an inputting parameter).
Parse Cloud Code:
Parse.Cloud.define("query_num_greater_than_local", function(request, response)
{
var DB = Parse.Object.extend("Recording_db");
var query= new Parse.Query(DB);
query.greaterThan("Ref_int",1234);
query.find(
{
success: function(results)
{
console.log("received " + results.length + " result(s)");
response.success("done" + results.length);
},
error: function(error)
{
console.log("error: " + error);
}
});
});
Android code:
ParseCloud.callFunctionInBackground("query_num_greater_than_local", new HashMap<String, Object>(), new FunctionCallback<String>()
{
public void done(String result, ParseException e)
{
if (e == null)
{
tv1.setText(""+result);
}
else
{
tv1.setText("ParseException"+e);
}
}
});
Question:
While the above codes return a correct count of items greater than 1234, I would like to ask whether can 1234 be replaced as a parameter? i.e. query for a result based on an inputting variable query criteria, say become query.greaterThan("Ref_int", 2345)?
If then, how could this variable inputting criteria be applied to the codes? Many thanks!

Whatsapp-like app

i am developing an app like "whatsapp" for which i want display contacts on my content (between header and footer) from my android phone so what can i do that task?
i tried this but it doesnt work.
function displayContact1() {
alert('Clicked');
var options = new ContactFindOptions();
options.filter="";
options.multiple=true;
var filter = [ "displayName", "phoneNumbers", "photos" ];
navigator.contacts.find(filter, displayContact, onContactError, options);
var myContacts = new Object();
// Default image path for the profile image
var defaultImagePath = $("#defaultImagePath").attr('src');
for (var i=0; i<contacts.length; i++)
{
if( contacts[i].phoneNumbers == null )
continue;
// Checks for the image
var img = contacts[i].photos != null ? contacts[i].photos[0].value : defaultImagePath;
if(contacts[i].phoneNumbers.length)
for (var j=0; j<contacts[i].phoneNumbers.length; j++)
{
var pNumber = contacts[i].phoneNumbers[j].value;
var name = contacts[i].displayName != null ? contacts[i].displayName: "No name";
// To sort the names based on the starting letter
// Stores the names in that array
var index = name.substring(0,1).toUpperCase();
if (typeof myContacts[index] == 'undefined')
{
myContacts[index] = new Array();
}
// cuts the large names
if( name.length > 35 )
{
name = name.substr(0,35)+"...";
}
// Push every details into an array.
myContacts[index].push({"name":name, "pNumber": pNumber, "img": img} );
}
}
var arrayKeys = new Array();
for (var key in myContacts )
{
arrayKeys.push( key );
}
// Sorts the array based on the key A, B , C etc
arrayKeys = arrayKeys.sort();
for( i = 0 ; i < arrayKeys.length ; i++ )
{
var records = myContacts[ arrayKeys[i] ];
$("#contacts").append ("<li class='letter-head'>"+ arrayKeys[i]+"</li>");
// Sort each names
records = records.sort( sortNames );
for( var r_key in records )
{
$("#contacts").append ( "<li><img src='"+ records[r_key].img+"' /> <span class='contact-name'>"+records[r_key].name + "</span><span class='contact-number'>" + records[r_key].pNumber + "</span></li>");
}
}
hide_loader();
$('.addressBook').effect("slide", {direction: "right"}, 500);
}
function sortNames(a, b )
{
return a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;
}
Please look up the Android Developer Site before asking next time.
Google can help here too.
There's a "Contact Managet" Sample from Google or THIS one.
Here's how you read the contact data: LINK
Here's how you create a custom listview: LINK
Here's a tutorial for a whole contacts list: LINK

Update phone contact (Android) via Phonegap

Using phonegap, I can get/filter a single contact from contact list. But how to update (add/remove) phone number field. Please help. Thanks alot.
Lets say 1 got a contact name John Smith with 2 phone number [('Home', '1111'), ('Work', '2222')].
When I try to remove the 'Work' number, just keep the 'Home' one. First get the contact, try to remove all number, then add the 'Home' number but I always get both 3 numbers [('Home', '1111'), ('Work', '2222'), ('Home', '1111')]
Weir that if I try to remove all number, then add nothing, it really remove all the number from contact ?
Here is my code
var phoneNumbers = [];
for (...){
phoneNum = {
type: ...,
value: ...,
pref: false
};
phoneNumbers.push(phoneNum);
}
contact = contacts_list[index]; //get the contact need to edit
//try to remove all current phone number
if (contact.phoneNumbers){
for (var i = 0; i < contact.phoneNumbers.length; i++){
delete contact.phoneNumbers[i];
//contact.phoneNumbers[i] = null; //i try this too
//contact.phoneNumbers[i] = []; //i try this too
}
}
//set new phone number
contact.phoneNumbers = phoneNumbers;
contact.save(...)
I also try create a new contact with only 1 number [('Home', '1111')], set id and rawId as same as i contact object I need to update, then save(). But i still get the same result [('Home', '1111'), ('Work', '2222'), ('Home', '1111')]
var contact = navigator.contacts.create();
var phoneNumbers = [];
phoneNumbers[0] = new ContactField('Home', '1111', false);
contact.phoneNumbers = phoneNumbers;
contact.id = ...
contact.rawId = ...
contact.save(...);
this also
contact = contacts_list[index]; //get the contact need to edit
//try to remove all current phone number
if (contact.phoneNumbers){
for (var i = 0; i < contact.phoneNumbers.length; i++){
delete contact.phoneNumbers[i];
//contact.phoneNumbers[i] = null; //i try this too
//contact.phoneNumbers[i] = []; //i try this too
}
}
var phoneNumbers = [];
phoneNumbers[0] = new ContactField('Home', '1111', false);
contact.phoneNumbers = phoneNumbers;
contact.save(...)
In the contact plugin of cordova, you can save the contact passing the original contact id, it will update the contact details in the database.
Here is an example:
//Set the options for finding conact
var options = new ContactFindOptions();
options.filter = 'Bob'; //name that you want to search
options.multiple = false;
var fields = ["id","displayName", "phoneNumbers"];
navigator.contacts.find(fields, sucessUpdate, onError, options);
function sucessUpdate(contacts) {
var contact = contacts[0]; //found contact array must be one as we disabled multiple false
// Change the contact details
contact.phoneNumbers[0].value = "999999999";
contact.name = 'Bob';
contact.displayName = 'Mr. Bob';
contact.nickname = 'Boby'; // specify both to support all devices
// Call the "save" function on the object
contact.save(function(saveSuccess) {
alert("Contact successful update");
}, function(saveError){
alert("Error when updating");
});
}
function onError(contactError)
{
alert("Error = " + contactError.code);
}

How to get the device contact using phonegap 2.0.0?

Am developing a android application using phonegap(Cordova 2.0.0). I need the retrieve the device contacts. I have tried with code given this doc
http://docs.phonegap.com/en/2.0.0/cordova_contacts_contacts.md.html#Contacts
my code as follows
$("#shareoptions3").live('click',function(){
var options = new ContactFindOptions();
options.multiple = true;
var fields = ["displayName","phoneNumbers"];//["displayName", "name","phoneNumbers"];
navigator.contacts.find(fields, onContactSuccess, onContactError, options);
});
function onContactSuccess(contacts) {//alert(contacts.length);
for (var i=0; i<contacts.length; i++) {
// display phone numbers
for (var j=0; j<contacts[i].phoneNumbers.length; j++) {
alert("Type: " + contacts[i].phoneNumbers[j].type + "\n" +
"Value: " + contacts[i].phoneNumbers[j].value + "\n" +
"Preferred: " + contacts[i].phoneNumbers[j].pref);
}
}
};
// onError: Failed to get the contacts
//
function onContactError(contactError) {
console.log('Error in getting contacts!');
}
I am getting message in Logcat like this :
Error in success callback: Contacts3 = TypeError: Cannot read property 'length' of null at file:///android_asset/www/JS/cordova-2.0.0.js:258
Please help me to sort out this problem.
One of your contact may not have a telephone number, and that is why you'll get a null value instead of a phone number.
So, in your for loop, one of the contacts[i].phoneNumbers.length wil generate an error.
I suggest you to first check if the phoneNumbers is null or not, before displaying / alerting it, by using:
if(contacts[i].phoneNumbers != null)
In the end, you may try something like this:
$("#shareoptions3").live('click',function(){
var options = new ContactFindOptions();
options.multiple = true;
var fields = ["displayName","phoneNumbers"];//["displayName", "name","phoneNumbers"];
navigator.contacts.find(fields, onContactSuccess, onContactError, options);
});
function onContactSuccess(contacts) {//alert(contacts.length);
for (var i=0; i<contacts.length; i++) {
// display phone numbers
if(contacts[i].phoneNumbers != null) // Checking if not null
for (var j=0; j<contacts[i].phoneNumbers.length; j++) {
alert("Type: " + contacts[i].phoneNumbers[j].type + "\n" +
"Value: " + contacts[i].phoneNumbers[j].value + "\n" +
"Preferred: " + contacts[i].phoneNumbers[j].pref);
}
}
};
// onError: Failed to get the contacts
//
function onContactError(contactError) {
console.log('Error in getting contacts!');
}
Hope this helps, let me know if this works for you.

Categories

Resources