Reputation: 73
I am trying to get all phone numbers and emails of contact with Xamarin.Android. I found this https://stackoverflow.com/a/2356760/4965222 but I can't apply this raw android recipe for Xamarin.Android because not found where I can get Phones._ID
, Phones.TYPE
, Phones.NUMBER
, Phones.LABEL
, People.Phones.CONTENT_DIRECTORY
. How to get this data without Xamarin.Mobile library?
Upvotes: 0
Views: 1998
Reputation: 73
After documentation research, I found the answer.
//filtering phones related to a contact
var phones = Application.Context.ContentResolver.Query(
ContactsContract.CommonDataKinds.Phone.ContentUri,
null,
ContactsContract.CommonDataKinds.Phone.InterfaceConsts.ContactId
+ " = " + contactId, null, null);
// getting phone numbers
while (phones.MoveToNext())
{
var number =
phones.GetString( //specify which column we want to get
phones.GetColumnIndex(ContactsContract.CommonDataKinds.Phone.Number));
// do work with number
}
phones.Close();
Upvotes: 1
Reputation: 5370
Here is the starting point
public List<PersonContact> GetPhoneContacts()
{
var phoneContacts = new List<PersonContact>();
using (var phones = ApplicationContext.ContentResolver.Query(ContactsContract.CommonDataKinds.Phone.ContentUri, null, null, null, null))
{
if (phones != null)
{
while (phones.MoveToNext())
{
try
{
string name = phones.GetString(phones.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.DisplayName));
string phoneNumber = phones.GetString(phones.GetColumnIndex(ContactsContract.CommonDataKinds.Phone.Number));
string[] words = name.Split(' ');
PersonContact contact = new PersonContact();
contact.FirstName = words[0];
if (words.Length > 1)
contact.LastName = words[1];
else
contact.LastName = ""; //no last name, is that ok?
contact.PhoneNumber = phoneNumber;
phoneContacts.Add(contact);
}
catch (Exception ex)
{
//something wrong with one contact, may be display name is completely empty, decide what to do
}
}
phones.Close(); //not really neccessary, we have "using" above
}
//else we cannot get to phones, decide what to do
}
return phoneContacts;
}
public class PersonContact
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
}
Upvotes: 1