Update phone contact (Android) via Phonegap - android

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

Related

Is there a unique identifier for Android phone contacts?

I have an app that reads the contact details of the phone. This code returns 744 as the id of a particular contact's row when accessed through Email.ContentUri.
var uriEmail = ContactsContract.CommonDataKinds.Email.ContentUri;
string[] projectionEmail = { ContactsContract.Contacts.InterfaceConsts.Id, ContactsContract.Contacts.InterfaceConsts.DisplayName, ContactsContract.Contacts.InterfaceConsts.PhotoUri, ContactsContract.CommonDataKinds.Email.Address };
var cursorEmail = this.Activity.ContentResolver.Query(uriEmail, projectionEmail, null, null, null);
// var contactList = new List<string>();
contacts = new ObservableCollection<Contact>();
if (cursorEmail.MoveToFirst())
{
do
{
//contactList.Add(cursor.GetString(cursor.GetColumnIndex(projection[2])));
contacts.Add(new Contact()
{
Id = cursorEmail.GetInt(cursorEmail.GetColumnIndex(projectionEmail[0])),
Name = cursorEmail.GetString(cursorEmail.GetColumnIndex(projectionEmail[1])),
Photo = cursorEmail.GetString(cursorEmail.GetColumnIndex(projectionEmail[2])),
Email = cursorEmail.GetString(cursorEmail.GetColumnIndex(projectionEmail[3])),
});
}
while (cursorEmail.MoveToNext());
}
ListView listEmail = v.FindViewById<ListView>(Resource.Id.listViewSelect);
listEmail.Adapter = new ContactAdapter(v.Context, contacts);
listEmail.ItemClick += OnClientListClick;
This code returns 752 as the id of the same contact when accessed through StructuredPostal.ContentUri.
var uriAddress = ContactsContract.CommonDataKinds.StructuredPostal.ContentUri;
string[] projectionAddress = { ContactsContract.Contacts.InterfaceConsts.Id, ContactsContract.Contacts.InterfaceConsts.DisplayName, ContactsContract.Contacts.InterfaceConsts.PhotoUri, ContactsContract.CommonDataKinds.StructuredPostal.Street, ContactsContract.CommonDataKinds.StructuredPostal.Postcode };
var cursorAddress = this.Activity.ContentResolver.Query(uriAddress, projectionAddress, null, null, null);
// var contactList = new List<string>();
properties = new ObservableCollection<Property>();
if (cursorAddress.MoveToFirst())
{
do
{
int n = cursorAddress.GetInt(cursorAddress.GetColumnIndex(projectionAddress[0]));
string str = cursorAddress.GetString(cursorAddress.GetColumnIndex(projectionAddress[1]));
if (n == nId)
{
//contactList.Add(cursor.GetString(cursor.GetColumnIndex(projection[2])));
properties.Add(new Property()
{
Id = cursorAddress.GetInt(cursorAddress.GetColumnIndex(projectionAddress[0])),
Name = cursorAddress.GetString(cursorAddress.GetColumnIndex(projectionAddress[1])),
Photo = cursorAddress.GetString(cursorAddress.GetColumnIndex(projectionAddress[2])),
Street = cursorAddress.GetString(cursorAddress.GetColumnIndex(projectionAddress[3])),
Postcode = cursorAddress.GetString(cursorAddress.GetColumnIndex(projectionAddress[4])),
});
}
}
while (cursorAddress.MoveToNext());
}
ListView listAddress = v.FindViewById<ListView>(Resource.Id.listViewSelect);
listAddress.Adapter = new PropertyAdapter(v.Context, properties);
listAddress.ItemClick += OnPropertyListClick;
Is there a unique identifier that's allocated to the contact in the Android phone?
If you wanna a unique id, you could use CONTACT_ID which is a reference to _ID of each contact.
CONTACT_ID:
https://developer.android.com/reference/android/provider/ContactsContract.RawContactsColumns.html#CONTACT_ID
_ID:https://developer.android.com/reference/android/provider/BaseColumns#_ID
If you want to use the unique id cross device, you could try to use the LOOKUP_KEY.
LOOKUP_KEY:
https://developer.android.google.cn/reference/android/provider/ContactsContract.ContactsColumns.html#LOOKUP_KEY
For more code details, you could check the link below. Get cross-device unique ID for Android phone contacts

How to fetch contacts and print them using flutter?

I would like to fetch contacts and populate them in a listview, I read the flutter documentation:
// Get all contacts on device
Iterable<Contact> contacts = await ContactsService.getContacts();
How can I access the contact name?
Contact is a class, and its fields are the following :
String displayName, givenName, middleName, prefix, suffix, familyName;
// Company
String company, jobTitle;
// Email addresses
Iterable<Item> emails = [];
// Phone numbers
Iterable<Item> phones = [];
// Post addresses
Iterable<PostalAddress> postalAddresses = [];
// Contact avatar/thumbnail
Uint8List avatar;
you can access the contact name by iterating throw the array contacts , and access each fields , as the following :
contacts.forEach((contact){
print(contact.displayName);
});
To get phone number ...this is my code:
import 'package:contacts_service/contacts_service.dart';
import 'package:permission_handler/permission_handler.dart';
void printContactsNumber() {
Iterable<Contact> contacts = await ContactsService.getContacts(withThumbnails: false);
List<Contact> contactsList = contacts.toList();
// now print first 50 number's contancts
for (int i = 0; i < 50; i++) {
contactsList[0].phones.first.value.toString()
}
}

Compare contact and select on click

i am creating app in which i have to compare my device contact to server data contact.i am doing this but only last data is coming,but i want to make comparison with every device contact to server contact.I am able to fetch data from device and from server but i don't know how to compare.
Here phonenumber is no coming from phonecursor and second is server data.
Objects.equals(phoneNumber, jsonObject1.getString("mobile"))
after the comparison i want to select any five contact from list and send it to another fragment.i don't know how to select item from recyclerview list.
first you have to store your all contact into DB.
then,
ArrayList<String> foundNumb = new ArrayList();
for (int A = 0; A < DB_Contact_List.size(); A++) {
// get contact from DB list one by one
DBContactBean dbDataBean = DB_Contact_List.get(A);
String DbNumb = dbDataBean.getmNumber().replaceAll("\\s+", "");
String ServrNumb = "";
ServerContactBean serverDataBeanM = null;
boolean found = false;
int BBB = 0;
if (!DbNumb.equals("")) {
innerLoop:
for (int B = 0; B < Server_Contact_List.size(); B++) {
// get contatct from Server list one by one
ServerContactBean serverDataBean = Server_Contact_List.get(B);
BBB = B;
serverDataBeanM = serverDataBean;
ServrNumb = serverDataBean.getPh_phone().replaceAll("\\s+", "");
// compare it
if (DbNumb.equalsIgnoreCase(ServrNumb)) {
found = true;
break innerLoop;
}
}
if (found) {
// if found do your task
foundNumb.add(DbNumb);
} else {
// not found
}
}
}

How to fetch only those Contacts having photo using Cordova Plugin Contacts?

Using options.filter working well for displayName, name, emails, phoneNumbers etc and returns only matched contacts, but it is not working for photos and retuning unmatched contacts too as I want to fetch only those contacts having photos. cordova-plugin-contacts
Function onSuccess (contacts) {
console.log(contacts);
};
function onError(contactError) {
alert('onError!');
};
// find all contacts with 'Bob' in any name field
var options = new ContactFindOptions();
options.filter = "content://";
options.multiple = true;
options.hasPhoneNumber = true;
var fields = [navigator.contacts.fieldType.photos];
navigator.contacts.find(fields, onSuccess, onError, options);

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

Categories

Resources