In my app I need to add contact to default google account and sync it.
Here my code:
public static void addContact(Context context, String DisplayName,String WorkNumber, String MobileNumber, String emailID,
String jobTitle, String company, String address){
ArrayList <ContentProviderOperation> ops = new ArrayList < ContentProviderOperation > ();
String account = getUsernameLong(context);
ops.add(ContentProviderOperation.newInsert(
ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.google")
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, account)
.build());
//------------------------------------------------------ Names
if (DisplayName != null) {
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(
ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
DisplayName).build());
}
..................
try {
context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
//requestSyncNow(context);
} catch (Exception e) {
e.printStackTrace();
try {
//Toast.makeText(context, "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (Exception e1) {
}
}
}
Here function getUsernameLong () that return google account
public static String getUsernameLong(Context context) {
AccountManager manager = AccountManager.get(context);
Account[] accounts = manager.getAccountsByType("com.google");
List<String> possibleEmails = new LinkedList<String>();
for (Account account : accounts) {
// account.name as an email address only for certain account.type values.
possibleEmails.add(account.name);
Log.i("DGEN ACCOUNT","CALENDAR LIST ACCOUNT/"+account.name);
}
if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
String email = possibleEmails.get(0);
return email;
}
return null;
}
This code add name to contact and on the phone I can see that on the phone it's on xxx@gmail.com account, but it's not sync with the remote account. I can't find it on gmail account as contact or on other device which same account
I also try to input statically google account xxxx@gmail.com but result will be the same, add to phone contact but not synch with google account.
UPDATE Code is OK, I forgot to enable synch of google account on my device
if you have multiple account open in device it's save in only first account not the default one account.
Your code works fine on my devices (Android 4.0.4 and 4.1.2), on Google server contacts for account appear automatically and from one device to other device. Thank you very much for the code, by the way.
IMHO the issue is not the code, but sync settings of your device.