PhoneGap : Fetch Contact list with optimize speed - android

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

Related

Chrome Android 6x version input value replace duplicate value

This problem happened with my phone (Samsung Galaxy Note 4)
I am using jQuery, I am trying to code such that if a person fill (keyup jquery) value on input, text will spilt into 4 digit number
example : 123412341234 will become 1234-1234-1234
but when i test my code
example : 123412341234
it become
1234-1123-4121-2341-2312-3412-3412-3412-3411-2341-2341-2123-4123-4123-1234-1234-1234
below is my code :
$('#account_bank_number').keyup(function(e){
e.preventDefault();
var account_bank_number = $(this).val();
var account_bank_number_filter = account_bank_number.replace(/-/g, "");
var account_bank_number_new = autoSplit(5, account_bank_number_filter, '-');
$('.debug-mode').html(account_bank_number_new);
}
function autoSplit(number, string, splitChar) {
var stringLength = string.length;
var countNumber = 1;
var newString = '';
for (var i = 0; i <stringLength ; i++) {
if (countNumber == number && string.charAt(i) != splitChar) {
newString = newString+splitChar+string.charAt(i);
countNumber = 2;
continue;
}
newString = newString + string.charAt(i);
countNumber++;
};
return newString;
}
What am I doing wrong?
Hi no sure if you need this but you can do a simple :
var str = "123412341234";
str.replace(/(.{4})/g,"$1-").slice(0,-1);
$(document).ready(function(){
//uncomment if you want do it onload page
//$( "#account_bank_number" ).keyup();
});
//test on click to the input
$( "#account_bank_number" ).click(function() {
$( "#account_bank_number" ).keyup(); //this is a trigger
});
$('#account_bank_number').keyup(function(e){
e.preventDefault();
var account_bank_number = $(this).val();
var account_bank_number_filter = account_bank_number.replace(/-/g, "");//no sure you need it ...
var account_bank_number_new = account_bank_number_filter.replace(/(.{4})/g,"$1-").slice(0,-1);
$('.debug-mode').html(account_bank_number_new);
//adding the value to the input comment if you dont need
this.value = account_bank_number_new;
});
.debug-mode{background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input id="account_bank_number" type="text" value="1234123412341234"/>
<div class="debug-mode"></div>
Simple regex "." is the string. "{4}" is the number to cut the string every 4 characters. "$1-" is the pattern. "$1" is the new string cutting and the "-" at this end is the character being added and the slice is for deleting the last characters added by your replace function. Regards

Taking too much time in loading phone device contact list in cordova

I am loading mobile device contact list in Cordova android application.Its Loading and displaying fine except the huge amount of time .For say 300 contact list it is taking 6 minutes of time which is very very bad for the user experience of the app.
Is there any way by which i can reduce the loading time and pace up the app.Any suggestion will be helpfull for me ..Thanks..
Here is updated code..
function drawListContent(contactListArray, filter) {
var contactList;
if (contactListArray) {
contListContainer.innerHTML = "";
for (var i = 0; i < contactListArray.length; i++) {
if (typeof(contactListArray[i]) == "string") {
contListContainer.innerHTML += contactListArray[i];
}
else {
contListContainer.appendChild(contactListArray[i]);
}
}
}
contactList = getElementChildren(contListContainer);
for (var i = 0; i < contactList.length; i++) {
filter = filter.toLowerCase();
var name = getDisplayedName(contactList[i]).toLowerCase().split(" ");
for (var j = 0; j < name.length; j++) {
if (name[j].indexOf(filter) === 0) {
contactList[i].style.display = "block";
break;
}
}
}
}

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

can not remove contacts, android phonegap

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. :)

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