How to edit existing Contacts in Android? - android

I am trying to edit existing phone contacts by using application. By using contact name am getting the corresponding contact id.Then am trying to update the existing contacts by using the contact id. But unfortunately it is not updating.
My code is as follows,
String select = "(" + ContactsContract.Contacts.DISPLAY_NAME + " == \"" + edt_nameDetail.getText() + "\" )";
Cursor c = getActivity().getApplicationContext().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
getActivity().startManagingCursor(c);
if (c.moveToNext()) {
ContactId = c.getString(0);
Log.e("Tag contact id ","edit contact id "+ ContactId);
}
try
{
String name = edt_nameDetail.getText().toString().trim();
String email = edt_contactEmailDetail.getText().toString().trim();
String number = edt_mobileNumberDetail.getText().toString().trim();
ContentResolver contentResolver = getActivity().getContentResolver();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] emailParams = new String[]{ContactId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE};
String[] nameParams = new String[]{ContactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
String[] numberParams = new String[]{ContactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<android.content.ContentProviderOperation>();
if(!email.equals("") &&!name.equals("")&& !number.equals(""))
{
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,emailParams)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
.build());
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,nameParams)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
.build());
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,numberParams)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number)
.build());
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(getActivity(), "Contact is successfully edited", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getActivity(), "Fail edit", Toast.LENGTH_SHORT).show();
}

If you are searching with email then update your .withSelection as
.withSelection(ContactsContract.CommonDataKinds.Email.ADDRESS + "=? AND " +
Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE + "'",
new String[]{email})
update all your withselection code corresponding to your search type

Note: after this, contact ID will changed.
public static boolean updateContactName(String contactId, String pre, String first, String mid, String last, String suf)
{
try
{
if (pre == null && first == null && mid == null && last == null && suf == null)
return false;
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] nameParams = new String[]{contactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<>();
android.content.ContentProviderOperation.Builder t ;
android.content.ContentProviderOperation b ;
t = android.content.ContentProviderOperation.newUpdate(Data.CONTENT_URI);
t = t.withSelection(where, nameParams);
if(pre != null)
t = t.withValue(StructuredName.PREFIX, pre.trim());
if(first != null)
t = t.withValue(StructuredName.GIVEN_NAME, first.trim());
if(mid != null)
t = t.withValue(StructuredName.MIDDLE_NAME, mid.trim());
if(last != null)
t = t.withValue(StructuredName.FAMILY_NAME, last.trim());
if(suf != null)
t = t.withValue(StructuredName.SUFFIX, suf.trim());
b = t.build();
ops.add(b);
ContentManager.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
return true;
}
catch (Exception e) {}
return false;
}

Related

Query on contact list for select contacts - Multiple URI Android?

How can I set query on ContactsContract.CommonDataKinds.Email and ContactsContract.CommonDataKinds.Phone in one query and get ID, Name, PhoneNumber and Email .... ?
Like bellow code :
private void getContactList() {
String id = "";
String name = "";
String phoneNo = "";
String mail = "";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
Cursor eCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
if (pCur != null) {
while (pCur.moveToNext()) {
phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phoneNo != null && !TextUtils.isEmpty(phoneNo)) {
//Log.i("ASDASDASDASDD", "id: " + id);
Log.i("ASDASDASDASDD", "Name: " + name);
Log.i("ASDASDASDASDD", "Phone Number: " + phoneNo);
Log.i("ASDASDASDASDD", "email: ");
} else {
phoneNo = "";
}
}
pCur.close();
} else {
phoneNo = "";
}
if (eCur != null) {
while (eCur.moveToNext()) {
mail = eCur.getString(eCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if (mail != null && !TextUtils.isEmpty(mail)) {
//Log.i("ASDASDASDASDD", "id: " + id);
Log.i("ASDASDASDASDD", "Name: " + name);
Log.i("ASDASDASDASDD", "Phone Number: " + phoneNo);
Log.i("ASDASDASDASDD", "email: " + mail);
} else {
mail = "";
}
}
eCur.close();
} else {
mail = "";
}
}
//}
}
if (cur != null) {
cur.close();
}
}
I need to have Phone, Name, Id, Email and ... together .
The Email and Phone tables are actually convenience uris for the Data table, which contains all data of all types (emails, phones, and more!)
String[] projection = new String[] { Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1 };
Cursor cur = getContentResolver().query(Data.CONTENT_URI, projection, Data.MIMETYPE + " IN ('" + Email.CONTENT_ITEM_TYPE + "' , '" + Phone.CONTENT_ITEM_TYPE +"')", null, null);
while ((cur != null) && cur.moveToNext()) {
long contactId = cur.getLong(0);
String name = cur.getString(1);
String type = cur.getString(2);
String data = cur.getString(3);
if (type == Email.CONTENT_ITEM_TYPE) {
Log.e("Data", "Found an email: " + contactId + ", " + name + ", " + type + ", " + data);
} else {
Log.e("Data", "Found a phone: " + contactId + ", " + name + ", " + type + ", " + data);
}
}
Resolved my problem :
private void XXXXX() {
StringBuilder phoneNo = new StringBuilder();
StringBuilder email = new StringBuilder();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null,
null);
if (phones != null) {
while (phones.moveToNext()) {
phoneNo.append("\n").append(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phones.close();
} else {
phoneNo = new StringBuilder();
}
Cursor emailC = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + id, null,
null);
if (emailC != null) {
while (emailC.moveToNext()) {
email.append("\n").append(emailC.getString(emailC.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
}
emailC.close();
} else {
email = new StringBuilder();
}
Log.e("ASDASASDAS",
"name : " + name
+ " \n " +
" phone : " + phoneNo
+ " \n " +
" email : " + email
+ " \n");
phoneNo = new StringBuilder();
email = new StringBuilder();
}
}
}

How to remove duplicate contact number from all type of contact without database?

How to remove duplicate number entry in Android when fetching contact number from contact book?
For example:
In contact book for
one name multiple contact.. ex-type-home-9428060123,
type-work-9428060123, I want to fetch unique contact number from all
type,android problematically? I use below code for fetching
information:
private void getContactsDetails() {
showLoader();
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null/*selection + " AND " +
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1"*/, null, "UPPER("
+ ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
ContactString = new ArrayList<>();
if (phones != null) {
if (phones.getCount() > 0) {
tvNoContact.setVisibility(View.GONE);
while (phones.moveToNext()) {
String Name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
HashSet<String> mobileNoSet = new HashSet<String>();
if (!mobileNoSet.contains(number)){
String s = number.replaceAll("\\W", "");
String lastTenCharContact = null;
if (s != null && s.length() > 10) {
lastTenCharContact = s.substring(s.length() - 10);
} else {
lastTenCharContact = s;
}
// String substring = s.substring(Math.max(s.length() - 10, 0));
Log.d(TAG, "getContactsDetails: " + lastTenCharContact);
String image_uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
ContactString.add(lastTenCharContact);
DeviceContact contactModel = new DeviceContact(Name.toUpperCase(), lastTenCharContact, image_uri);
contactModelsList.add(contactModel);
mobileNoSet.add(number);
Log.d(TAG, "Name : " + Name + ", Number : " + number + ", Photo : " + image_uri);}
}
hideLoader();
AllContactsyncapiCall();
} else {
tvNoContact.setVisibility(View.VISIBLE);
}
} }
for remove duplicate Number just make hashset before your loop:
HashSet<String> mobileNoSet = new HashSet<String>();
Now when you put contact in model use below code:
if (!mobileNoSet.contains(number)){
String s = number.replaceAll("\\W", "");
String lastTenCharContact = null;
if (s != null && s.length() > 10) {
lastTenCharContact = s.substring(s.length() - 10);
} else {
lastTenCharContact = s;
}
// String substring = s.substring(Math.max(s.length() - 10, 0));
Log.d(TAG, "getContactsDetails: " + lastTenCharContact);
String image_uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
ContactString.add(lastTenCharContact);
DeviceContact contactModel = new DeviceContact(Name.toUpperCase(), lastTenCharContact, image_uri);
contactModelsList.add(contactModel);
mobileNoSet.add(number);
}
This is new code in which i m getting duplicate number :-
private void getContactsDetails() {
// showLoader();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null/*selection + " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1"*/, null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
ContactString = new ArrayList<>();
nameString = new ArrayList<>();
if (phones != null) {
if (phones.getCount() > 0) {
tvNoContact.setVisibility(View.GONE);
HashSet<String> mobileNoSet = new HashSet<String>();
while (phones.moveToNext()) {
String Name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (!mobileNoSet.contains(number)) {
// String s = number.replaceAll("\\W", "");
String s = number.replaceAll("[^[+]\\d]", "");
String lastTenCharContact = null;
lastTenCharContact = s;
/*if (s != null && s.length() > 10) {
lastTenCharContact = s.substring(s.length() - 10);
} else {
lastTenCharContact = s;
}*/
// String substring = s.substring(Math.max(s.length() - 10, 0));
Log.d(TAG, "getContactsDetails: " + lastTenCharContact);
String image_uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
ContactString.add(lastTenCharContact);
// nameString.add(Name);
contactModel = new DeviceContact(Name.toUpperCase(), lastTenCharContact, image_uri);
contactModelsList.add(contactModel);
mobileNoSet.add(number);
Log.d(TAG, "Name : " + Name + ", Number : " + number + ", Photo : " + image_uri);
}
}
// hideLoader();
AllContactsyncapiCall();
} else {
tvNoContact.setVisibility(View.VISIBLE);
}
}
}

Fetch contact list along with their primary email and phone number in a single query from the ContactProvider

I am trying to get the list of contacts with their phone and email details to display them in a list. What i have done now is do three separate queries.
Get list of contacts to contactCursor from Contacts.CONTENT_URI
Get all phone numbers to phoneCursor from Phone.CONTENT_ITEM_TYPE
Get all emails to emailCursor from Email.CONTENT_ITEM_TYPE
Then i will am Looping through the contactCursor. For every contact, i will loop through the phoneCursor and emailCursor to get the primary phone number and email. But this takes some time to load and is clearly visible when the number of contacts is large. Is there any way that i can get all these details in the first step itself.
Below is the code snippet:
Cursor contacts = resolver.query(Contacts.CONTENT_URI,
CONTACT_PROJECTION, Contacts.HAS_PHONE_NUMBER + " != 0", null, Contacts._ID + " ASC");
Cursor phone = resolver.query(Data.CONTENT_URI, PHONE_PROJECTION,
Data.MIMETYPE + "=? ",
new String[]{Phone.CONTENT_ITEM_TYPE},
Data.CONTACT_ID + " ASC");
Cursor email = resolver.query(Data.CONTENT_URI, EMAIL_PROJECTION,
Data.MIMETYPE + "=? ",
new String[]{Email.CONTENT_ITEM_TYPE},
Data.CONTACT_ID + " ASC");
if (contacts!=null && contacts.moveToFirst()) {
do {
String contactId = contacts.getString(0);
if(phone!=null && phone.moveToFirst()){
do{
if(contactId.equalsIgnoreCase(phone.getString(0))){
contact.setMobile(phone.getString(1));
break;
}
}while(phone.moveToNext());
}
if(email!=null && email.moveToFirst()){
do{
if(contactId.equalsIgnoreCase(email.getString(2))){
contact.setEmailWork(email.getString(1));
break;
}
}while(email.moveToNext());
}
} while (contacts.moveToNext());
Below is the code to fetch all the contacts including email.
private void getContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String id = null, name = null, email = null, phone = null, note = null, orgName = null, title = null;
String Phone1 = "unknown", Phone2 = "unknown", Phone3 = "unknown", type1 = "unknown", type2 = "unknown", type3 = "unknown";
int size = cur.getCount();
StringBuilder addbuffer = null;
if (cur.getCount() > 0) {
int cnt = 1;
while (cur.moveToNext()) {
email = "";
name = "";
cnt++;
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (name != null && name != "") {
// if (!checkEmail(name)) {
// email = "";
//
// } else {
email = name;
name = "";
// }
}
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name);
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[] { id }, null);
Phone1 = " ";
Phone2 = " ";
Phone3 = " ";
while (pCur.moveToNext()) {
String phonetype = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String MainNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phonetype.equalsIgnoreCase("1")) {
Phone1 = MainNumber;
type1 = "home";
} else if (phonetype.equalsIgnoreCase("2")) {
Phone2 = MainNumber;
type2 = "mobile";
} else {
Phone3 = MainNumber;
type3 = "work";
}
}
pCur.close();
}
Cursor addrCur = cr.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID
+ " = ?", new String[] { id }, null);
if (addrCur.getCount() == 0) {
addbuffer.append("unknown");
} else {
int cntr = 0;
while (addrCur.moveToNext()) {
cntr++;
String poBox = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
if (poBox == null) {
poBox = " ";
}
String street = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
if (street == null) {
street = " ";
}
String neb = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD));
if (neb == null) {
neb = " ";
}
String city = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
if (city == null) {
city = " ";
}
String state = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
if (state == null) {
state = " ";
}
String postalCode = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
if (postalCode == null) {
postalCode = " ";
}
String country = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
if (country == null) {
country = " ";
}
String type = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
if (type == null) {
type = " ";
}
}
}
addrCur.close();
String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE };
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
note = " ";
if (noteCur.moveToFirst()) {
note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
if (note == null) {
note = " ";
}
}
noteCur.close();
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[] { id, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };
Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI, null, orgWhere, orgWhereParams, null);
orgName = " ";
if (orgCur.moveToFirst()) {
orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
if (orgName == null) {
orgName = " ";
}
orgCur.close();
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[] { id }, null);
email = "unknown";
while (emailCur.moveToNext()) {
email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
if (email == null) {
email = "unknown";
}
if (emailType.equalsIgnoreCase("1")) {
} else {
}
}
// add
emailCur.close();
}
}
}

Android 4.1+/ContactContract: Lookup group to given contactId (derived from lookup a number)

The following function has a phone number as input parameter (e.g. +436641234567 or +436641234567) and performs two lookups in the Contacts database: first, identify the user belonging to this number (this already works) and then to use the id of the user to get all groups this contact is assigned to (and this does not work). Test gives back the correct id (again), however, the group is "null".
public String getNameGroupByNumber(Context context, String number) {
String name = "?";
String contactId = "0";
String group = "0";
String test = "0";
// Step 1: LookUp Name to given Number
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] contactProjection = new String[] {BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME };
Cursor contactLookup = contentResolver.query(uri, contactProjection, null, null, null);
try {
if (contactLookup != null && contactLookup.getCount() > 0) {
contactLookup.moveToNext();
name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
Log.d(TAG, "Name: " +name + " ContactId: " + contactId); // works as expected
// Step 2: Lookup group memberships of the contact found in step one
Uri groupURI = ContactsContract.Data.CONTENT_URI;
String[] groupProjection = new String[]{ ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID , ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID};
Cursor groupLookup = contentResolver.query(groupURI, groupProjection, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID+"="+contactId, null, null);
try {
if (groupLookup != null && groupLookup.getCount() > 0) {
groupLookup.moveToNext();
test = groupLookup.getString(groupLookup.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
group = groupLookup.getString(groupLookup.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID));
Log.d(TAG, "Group found with Id: " + test + " and GroupId: " + group); // test is again the contactID from above but group is null
}
} finally {
if (groupLookup != null) {
groupLookup.close();
}
}
return name;
}
Cursor groupLookup = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID ,
ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID
},
ContactsContract.Data.MIMETYPE + "=? AND " + ContactContract.Data.CONTACT_ID + "=?",
new String[]{
ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE,
contact_id
}, null
);
Use this groupLookup cursor instead.
Cursor groupCursor = getContentResolver().query(
ContactsContract.Groups.CONTENT_URI,
new String[]{
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE
}, ContactsContract.Groups._ID + "=" + _id, null, null
);
groupCursor helps to get Group title from _id.

How to update existing contact?

I have one existing contact, I need to add a work address to that existing contact. I am using the following code, but it's not working.
String selectPhone = Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE +
"'" + " AND " + ContactsContract.CommonDataKinds.StructuredPostal.TYPE + "=?";
String[] phoneArgs = new String[]
{String.valueOf(ContactId), String.valueOf(
ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)};
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, STREET)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, CITY)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, REGION)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, POSTCODE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, COUNTRY)
.build());
this.context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Any solution for this?
/**
* #param name name of the contact
* #param number mobile phone number of contact
* #param email work email address of contact
* #param ContactId id of the contact which you want to update
* #return true if contact is updated successfully<br/>
* false if contact is not updated <br/>
* false if phone number contains any characters(It should contain only digits)<br/>
* false if email Address is invalid <br/><br/>
*
* You can pass any one among the 3 parameters to update a contact.Passing all three parameters as <b>null</b> will not update the contact
* <br/><br/><b>Note: </b>This method requires permission <b>android.permission.WRITE_CONTACTS</b><br/>
*/
public boolean updateContact(String name, String number, String email,String ContactId)
{
boolean success = true;
String phnumexp = "^[0-9]*$";
try
{
name = name.trim();
email = email.trim();
number = number.trim();
if(name.equals("")&&number.equals("")&&email.equals(""))
{
success = false;
}
else if((!number.equals(""))&& (!match(number,phnumexp)) )
{
success = false;
}
else if( (!email.equals("")) && (!isEmailValid(email)) )
{
success = false;
}
else
{
ContentResolver contentResolver = activity.getContentResolver();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] emailParams = new String[]{ContactId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE};
String[] nameParams = new String[]{ContactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
String[] numberParams = new String[]{ContactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<android.content.ContentProviderOperation>();
if(!email.equals(""))
{
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,emailParams)
.withValue(Email.DATA, email)
.build());
}
if(!name.equals(""))
{
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,nameParams)
.withValue(StructuredName.DISPLAY_NAME, name)
.build());
}
if(!number.equals(""))
{
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,numberParams)
.withValue(Phone.NUMBER, number)
.build());
}
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
}
}
catch (Exception e)
{
e.printStackTrace();
success = false;
}
return success;
}
// To get COntact Ids of all contact use the below method
/**
* #return arraylist containing id's of all contacts <br/>
* empty arraylist if no contacts exist <br/><br/>
* <b>Note: </b>This method requires permission <b>android.permission.READ_CONTACTS</b>
*/
public ArrayList<String> getAllConactIds()
{
ArrayList<String> contactList = new ArrayList<String>();
Cursor cursor = activity.managedQuery(ContactsContract.Contacts.CONTENT_URI, null, null, null, "display_name ASC");
if (cursor != null)
{
if (cursor.moveToFirst())
{
do
{
int _id = cursor.getInt(cursor.getColumnIndex("_id"));
contactList.add(""+_id);
}
while(cursor.moveToNext());
}
}
return contactList;
}
private boolean isEmailValid(String email)
{
String emailAddress = email.toString().trim();
if (emailAddress == null)
return false;
else if (emailAddress.equals(""))
return false;
else if (emailAddress.length() <= 6)
return false;
else {
String expression = "^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?#[a-z][a-z|0-9|]*\\.([a-z][a-z|0-9]*(\\.[a-z][a-z|0-9]*)?)$";
CharSequence inputStr = emailAddress;
Pattern pattern = Pattern.compile(expression,
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches())
return true;
else
return false;
}
}
private boolean match(String stringToCompare,String regularExpression)
{
boolean success = false;
Pattern pattern = Pattern.compile(regularExpression);
Matcher matcher = pattern.matcher(stringToCompare);
if(matcher.matches())
success =true;
return success;
}
//Sorry for my bad english
// It seems that in the first post you forgot to add the MimeType in operation.
String selectPhone = Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE + "'" ;
String[] phoneArgs = new String[]{String.valueOf(rawContactId)};
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, STREET)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, CITY)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, REGION)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, POSTCODE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, POSTCODE)
**
//Just add this line .withValue(Data.MIMETYPE,
"vnd.android.cursor.item/postal-address_v2")
**
.build());
this.context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Please check this and let me know the result
Finally I found the appropriate solution..Much thanks to this How to modify existing Contact
The secret is that you have to pass two values for .withSelection as shown below:
.withSelection(Data.RAW_CONTACT_ID + " = ?", new String[] {String.valueOf(id)})
.withSelection(Data._ID + " = ?", new String[] {mDataId})
where by Data._ID value mDataId is obtained this way:
Cursor mDataCursor = this.context.getContentResolver().query(
Data.CONTENT_URI,
null,
Data.RAW_CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ?",
new String[] { String.valueOf(id), ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE},
null);
if(mDataCursor.getCount() > 0) {
mDataCursor.moveToFirst();
mDataId = getCursorString(mDataCursor, Data._ID);
MLog.v("Data", "Found data item with MIMETYPE");
mDataCursor.close();
} else {
MLog.v("Data", "Data doesn't contain MIMETYPE");
result = ERROR;
mDataCursor.close();
}
And getCursorString method is something like:
private static String getCursorString(Cursor cursor, String columnName) {
int index = cursor.getColumnIndex(columnName);
if(index != -1) return cursor.getString(index);
return null;
}
This and only this is the trick..
Each field (email, name, adreess) has its own mime type, which you should use in order to update the field.
We will work with Data table, where each Data.RAW_CONTACT_ID represents a detail about some contact.
So, we need to find the Data.RAW_CONTACT_ID where the id is the id of the contact you want to edit.
I hope this code should be helpful to you.
String selectPhone = Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE + "'" ;
String[] phoneArgs = new String[]{String.valueOf(rawContactId)};
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, STREET)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, CITY)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, REGION)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, POSTCODE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, POSTCODE)
.build());
this.context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
If a new contact has been created, but without address, and now you want to add an address to that contcat. In this case use the same query as above, but just change newUpdate to newInsert, since such row isn't exist yet.
you should use "Data.RAW_CONTACT_ID" instead of "Data.CONTACT_ID" in the clause of selection.
Maybe you could use Intent and its ACTION_EDIT to get your user Edit the work address...

Categories

Resources