How to update contact number using Android - android

I am learning android. I am trying to upadate contact number programmatically. Could anyone help me please how can I do that.
My effort is:
String lNumber = pCur.getString( pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContentValues values = new ContentValues();
Uri lPhoneUri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, ContactsContract.CommonDataKinds.Phone.NUMBER);
values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "45323333"));
getContentResover().update(lPhoneUri, values, ContactsContract.CommonDataKinds.Phone.NUMBER+"=?", new String[] { lNumber });

I think you are pretty much there. The following uses the new API to update the WORK phone number of a contact, assume that that contact already has a work phone number.
public void updateContact (String contactId, String newNumber, Activity act)
throws RemoteException, OperationApplicationException{
//ASSERT: #contactId alreay has a work phone number
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String selectPhone = Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "='" +
Phone.CONTENT_ITEM_TYPE + "'" + " AND " + Phone.TYPE + "=?";
String[] phoneArgs = new String[]{contactId, String.valueOf(Phone.TYPE_WORK)};
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(Phone.NUMBER, newNumber)
.build());
act.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}

Try this
String where = ContactsContract.Data.DISPLAY_NAME + "=? AND " +
ContactsContract.Data.MIMETYPE + "=? AND " +
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + "=?";
String[] params = new String[] {
Cname,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
};
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,"9999999999")
// .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "Sample Name 21")
.build()
);
//email
String where3 = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ?";
String[] params3 = new String[] {
Cname,
"vnd.android.cursor.item/email_v2"
};
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where3, params3)
.withValue(ContactsContract.CommonDataKinds.Email.DATA,"a#b.com")
.build()
);
By using this I am able to update the contact details.

Just small change, if you need to update some other phone than work phone, you can have method that has this as a parameter.
public void updateContact (String contactId, String newNumber, String phoneType)
throws RemoteException, OperationApplicationException{
//ASSERT: #contactId alreay has a work phone number
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String selectPhone = Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "='" +
Phone.CONTENT_ITEM_TYPE + "'" + " AND " + Phone.TYPE + "=?";
String[] phoneArgs = new String[]{contactId, phoneType};
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(Phone.NUMBER, newNumber)
.build());
this.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}

This class may help to update the contact.
public class UpdateContact extends Activity {
private EditText txtName,txtPh;
private Button btnUpdate;
private TextView txt;
private static final String TAG_ID="id";
private static final String TAG_NAME = "name";
private static final String TAG_PHNO = "phNo";
private static int id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_contact);
txtName=(EditText)findViewById(R.id.txtNname);
txtPh=(EditText)findViewById(R.id.txtNPhNo);
btnUpdate=(Button)findViewById(R.id.btnUpdate);
txt=(TextView)findViewById(R.id.txtId);
Intent i=getIntent();
id=i.getIntExtra(TAG_ID,0);
txtName.setText(i.getStringExtra(TAG_NAME));
txtPh.setText(i.getStringExtra(TAG_PHNO));
//to update contact on button click you can apply this
btnUpdate.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
DatabaseHandler handler=new DatabaseHandler(UpdateContact.this);
Contact contact=new Contact();
contact.setID(id);
contact.setName(txtName.getText().toString());
contact.setPhNo(txtPh.getText().toString());
handler.UpdateContact(contact);
finish();
}
});
}
}

Here's how you update your Phone.Home.
val rawContactId = "101"
val contentProviderOperation = ArrayList<ContentProviderOperation>()
val where = ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Contacts.Data.MIMETYPE + "=" +
"'${ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}'" + " AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + "=?"
val params = arrayOf(rawContactId, "${ContactsContract.CommonDataKinds.Phone.TYPE_HOME}")
contentProviderOperation.add(
ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "+60123456789")
.build()
)
try {
contentResolver.applyBatch(ContactsContract.AUTHORITY, contentProviderOperation)
showToastyMessage("Contact Update Successfully")
} catch (exception: Exception) {
showToastyMessage(exception.message.toString())
}

Related

Performance of update existing contact in Android so slow

i have a problem in update existing contact in Android. My code execute about 400 contact but it take me about 20s to update it. Here is my code.
public class Contact {
private long contactId;
private String phoneNumber;
private int phoneType;
}
Then i try to update each contact filter by ID and Type:
ArrayList list = arrayLists[0];
for (int i = 0; i < list.size(); i++) {
Contact contact = list.get(i);
long contactID = contact.getContactId();
String newPhoneNumber = contact.getPhoneNumber();
int phoneType = contact.getPhoneType();
updateContact(contactID, newPhoneNumber, phoneType);
}
Here is my updateContact funtion:
private void updateContact(long contactID, String newPhoneNumber, int phoneType) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " + ContactsContract.CommonDataKinds.Phone.TYPE + " = ?";
String[] whereParams = new String[]{contactID + "", phoneType + ""};
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, newPhoneNumber);
Uri dataUri = ContactsContract.Data.CONTENT_URI;
cr.update(dataUri, contentValues, where, whereParams);
}
I tried other method to update contact but it also take same time ( about 20s for 400 contact)
private void updateContact(long contactID, String newPhoneNumber, int phoneType) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = ?";
String[] params = new String[]{contactID + "", phoneType + ""};
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, newPhoneNumber)
.build());
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
What should i do, how can i improve the performance of update job. I expert it can update 400 contact in 3-5s

How to edit existing Contacts in 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;
}

Selecting/Joining tables from contacts table but get no ouput - Android

I'm trying to go over all contacts using the contacts, raw_contacts and data tables.
From reading online I believe that Contacts._id is connected with RawContacts.contact_id and Data.raw_contact_id is connected with RowContacts._id. Am I right?
Believing in this I built this method:
public void testingContactsDatabase(String contactId)
{
final String[] projection = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME,
Data.RAW_CONTACT_ID,
Data.MIMETYPE,
StructuredName.DISPLAY_NAME,
StructuredName.FAMILY_NAME,
StructuredName.GIVEN_NAME,
StructuredName.MIDDLE_NAME,
StructuredName.PREFIX, // Common prefixes in English names are "Mr", "Ms", "Dr" etc.
StructuredName.SUFFIX // Common suffixes in English names are "Sr", "Jr", "III" etc.
};
final String selection = Contacts._ID + " = " + contactId + " AND "
+ Contacts._ID + " = " + RawContacts.CONTACT_ID + " AND "
+ Data.RAW_CONTACT_ID + " = " + RawContacts._ID;
final Cursor curStructuredName = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
projection,
selection, null,
//new String[] {contactId, ContactsContract.RawContacts.CONTACT_ID, RawContacts._ID},
null
);
if(curStructuredName.moveToFirst())
{
Log.d("XYZ", "Found something");
}
}
But it never finds anything. I'm not sure if I'm using the correct URI, I've tried with different URIs and either got exceptions or same ouput.
Can someone point me out where I'm doing something wrong?
Thanks
I've solved my problem. Here is my code working now:
// Get the structured name fields
public ArrayList<String> getStructuredName(String contactId)
{
ArrayList<String> structuredList = new ArrayList<String>();
final String[] projection = new String[] {
StructuredName.DISPLAY_NAME,
StructuredName.FAMILY_NAME,
StructuredName.GIVEN_NAME,
StructuredName.MIDDLE_NAME,
StructuredName.PREFIX, // Common prefixes in English names are "Mr", "Ms", "Dr" etc.
StructuredName.SUFFIX // Common suffixes in English names are "Sr", "Jr", "III" etc.
};
final String filter = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ?";
final String parameters[] = {StructuredName.CONTENT_ITEM_TYPE, contactId};
Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
projection, filter, parameters, null);
if(cursor.moveToFirst())
{
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
final String displayName = cursor.getString(cursor.getColumnIndex(StructuredName.DISPLAY_NAME));
final String familyName = cursor.getString(cursor.getColumnIndex(StructuredName.FAMILY_NAME));
final String givenName = cursor.getString(cursor.getColumnIndex(StructuredName.GIVEN_NAME));
final String middleName = cursor.getString(cursor.getColumnIndex(StructuredName.MIDDLE_NAME));
final String prefix = cursor.getString(cursor.getColumnIndex(StructuredName.PREFIX));
final String suffix = cursor.getString(cursor.getColumnIndex(StructuredName.SUFFIX));
structuredList.add(displayName);
structuredList.add(familyName);
structuredList.add(givenName);
structuredList.add(middleName);
structuredList.add(prefix);
structuredList.add(suffix);
Log.d(tag, "/////////////////////////////////////////////////////");
Log.d(tag, "displayName: " + displayName );
Log.d(tag, "familyName: " + familyName );
Log.d(tag, "givenName: " + givenName );
Log.d(tag, "middleName: " + middleName );
Log.d(tag, "prefix: " + prefix );
Log.d(tag, "suffix: " + suffix );
Log.d(tag, "/////////////////////////////////////////////////////");
}
}
cursor.close();
return structuredList;
}

How to access MISSED_CALL Log in Android

I am developing an app in which i want to access MISSED_CALL log. Using below code....
private Cursor getItemsToSync() {
G = "Log method accessing";
ContentResolver r = getContentResolver();
String selections = String.format("%s > ?", CallLog.Calls.DATE,CallLog.Calls.MISSED_TYPE);
String[] selectionArgs = new String[] { String.valueOf(getMaxSyncedDate())};
String sortOrder = SmsConsts.DATE + " LIMIT " + PrefStore.getMaxItemsPerSync(this);
N = CallLog.Calls.CACHED_NAME;
return r.query(Uri.parse("content://call_log/calls"), null,selections,selectionArgs, sortOrder);}
its provide All Call Log. Please suggest me how to get only MISSED_CALL Call log. Thanks in advance
String[] strFields = {android.provider.CallLog.Calls.CACHED_NAME, android.provider.CallLog.Calls.NUMBER,android.provider.CallLog.Calls.DATE, android.provider.CallLog.Calls.TYPE
};
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor mCallCursor = getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI,strFields, null, null, strOrder);
if (mCallCursor.moveToFirst()) {
do {
boolean missed = mCallCursor.getInt(mCallCursor.getColumnIndex(CallLog.Calls.TYPE)) == CallLog.Calls.MISSED_TYPE;
if (missed) {
String name = mCallCursor.getString(mCallCursor
.getColumnIndex(CallLog.Calls.CACHED_NAME));
String number = mCallCursor.getString(mCallCursor
.getColumnIndex(CallLog.Calls.NUMBER));
Log.d("PhoneLog", "You have a missed call from " + name + " on " + number // + " at " + time); }
} while (mCallCursor.moveToNext());
}

How to delete a contact?

I'm working at android 2.1 ContactContract, when I had not set account(for example: gmail account) to android emulator then, new a contact, but could not delete this contact at DB.
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String[] args = new String[] {id};
ops.add(ContentProviderOperation.newDelete(Data.CONTENT_URI)
.withSelection(Data.CONTACT_ID + "=?", args)
.build());
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
.withSelection(RawContacts.CONTACT_ID + "=?", args)
.build());
ops.add(ContentProviderOperation.newDelete(Contacts.CONTENT_URI)
.withSelection(Contacts._ID + "=?", args)
.build());
Deleting the contact from RawContacts will delete the data from Data, Contacts table.
ArrayList ops = new ArrayList(); String[] args = new String[] {id};
// if id is raw contact id
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI).withSelection(RawContacts._ID + "=?", args) .build());
OR
// if id is contact id
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI).withSelection(RawContacts.CONTACT_ID + "=?", args) .build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
public static boolean fullDeleteContactByRawId(String rawId)
{
Uri rawUri = RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
String where = RawContacts._ID + " = ?";
String[] args = new String[]{rawId};
try
{
ContentManager.delete(rawUri, where, args);
}
catch(Exception e)
{
return false;
}
return true;
}
notice:
After full delete ,this contact can not sync
I use this to delete a phone number from an existing contact, but not the contact itself:
ArrayList ops = new ArrayList();
String[] args = new String[]{
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
number,
Integer.toString(ContactsContract.CommonDataKinds.Phone.TYPE_MAIN),
raw_contact_id
};
ops.add(
ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.MIMETYPE + "=? AND "
+ ContactsContract.CommonDataKinds.Phone.NUMBER + "=? AND "
+ ContactsContract.CommonDataKinds.Phone.TYPE + "=? AND "
+ ContactsContract.Data.RAW_CONTACT_ID + "=?"
, args)
.build());
c.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

Categories

Resources