Problem adding contacts informations - android

I'm trying to add some contacts from an xml file which have been serialize with Simple xml framework and there is a weird error :
ERROR/ContentProviderOperation(10727): mType: 1, mUri: content://com.android.contacts/data, mSelection: null, mExpectedCount: null, mYieldAllowed: false, mValues: data1=Karl Koffi Marx Antoine Carter mimetype=vnd.android.cursor.item/name, mValuesBackReferences: raw_contact_id=1, mSelectionArgsBackReferences: null
This is the code
ContactList contactList = serializer.read(ContactList.class, xmlFile);
int nbreContacts = contactList.contact.length;
for(int i=0;i<nbreContacts;i++)
{
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
id = contactList.contact[i].getId();
name = contactList.contact[i].getName();
addName(Integer.parseInt(id), name);
flush(c);
}
private void addName(int contactId, String displayName)
{
if(displayName != null)
{
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, contactId)
.withValueData.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
.build());
}
}
private void flush(Context c)
{
ContentResolver cr = c.getContentResolver();
try
{
cr.applyBatch(ContactsContract.AUTHORITY, ops);
}
catch (RemoteException e)
{
Log.e("Writing", "Remote Error writting data ", e);
}
catch (OperationApplicationException e)
{
Log.e("Writing", "OAE Error writting data", e);
}
}
Any help would be appreciate.

Thanks to #Reno on the chat room.
withValueBackReference(Data.RAW_CONTACT_ID, contactId) changed to .withValueBackReference(Data.RAW_CONTACT_ID, 0)
I first thought RAW_CONTACT_ID was refering to the contact id that's why I was wrong. Problem solved and hope that will help someone else :)

Related

Add new contacts (36 items)

im trying to add new contacts to the phone but he does only the first 12 items.
i want to try all current 36 items and maybe more add to the phone contacts.
while ((line = bufferedReader.readLine()) != null) {
System.out.println("[[DEBUG]] [DW-UPDATE] LINE: " + line);
String[] split = line.split(";", -1);
split[2] = split[2].replace("/", "").replace("-", "");
if (!contactExists(mActivity, split[2])) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(split[0]))
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, split[1])
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(split[0]))
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, split[2])
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
.build());
try {
mActivity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}
}
function contactExists:
public boolean contactExists(Activity _activity, String number) {
Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] mPhoneNumberProjection = { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup.DISPLAY_NAME };
Cursor cur = _activity.getContentResolver().query(lookupUri, mPhoneNumberProjection, null, null, null);
try {
if (cur.moveToFirst()) {
return true;
}
} finally {
if (cur != null)
cur.close();
}
return false;
}// contactExists
what i must do, to work this better?
Your problem is with your back references when adding the additional contact data. The back reference should refer to the position of your RawContacts.CONTENT_URI insert within your list of operations (ops), not the position of the contact within your raw data file. You can fix this by keeping track of the size of ops through each iteration:
if (!contactExists(mActivity, split[2])) {
int backRef = ops.size();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(...)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
.withValue(...)
.build()
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
.withValue(...)
.build());
try {
mActivity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}

adding contact automatically in phone book in android app

I need to add a contact automatically in phone book by my app....I found this link..
How to add new contacts in android
using this, I am able to add phone no.,name,email etc. But don't know how to add photo.
Firstly convert your image to bitmap and then use below code for adding photo to your contact.
OnClickListener addClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Getting reference to Name EditText
EditText etName = (EditText) findViewById(R.id.et_name);
// Getting reference to Mobile EditText
EditText etMobile = (EditText) findViewById(R.id.et_mobile);
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
int rawContactID = ops.size();
// Adding insert operation to operations list
// to insert a new raw contact in the table ContactsContract.RawContacts
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null)
.build());
// Adding insert operation to operations list
// to insert display name in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, etName.getText().toString())
.build());
// Adding insert operation to operations list
// to insert Mobile Number in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, etMobile.getText().toString())
.withValue(Phone.TYPE, CommonDataKinds.Phone.TYPE_MOBILE)
.build());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if(mBitmap!=null){ // If an image is selected successfully
mBitmap.compress(Bitmap.CompressFormat.PNG , 75, stream);
// Adding insert operation to operations list
// to insert Photo in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.Data.MIMETYPE,Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO,stream.toByteArray())
.build());
try {
stream.flush();
}catch (IOException e) {
e.printStackTrace();
}
}
try{
// Executing all the insert operations as a single database transaction
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(getBaseContext(), "Contact is successfully added", Toast.LENGTH_SHORT).show();
}catch (RemoteException e) {
e.printStackTrace();
}catch (OperationApplicationException e) {
e.printStackTrace();
}
}
};
For more details please refer below link
http://wptrafficanalyzer.in/blog/programatically-adding-contacts-with-photo-using-contacts-provider-in-android-example/
Use following code this takes picture as photoByteArray for the method
private void addContact2() {
final String displayName = "XYZA";
final String mobileNumber = "666666";
final byte[] photoByteArray; // initalized elsewhere
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "")
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "")
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
//.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photoByteArray)
.build());
Uri newContactUri = null;
ContentProviderResult[] res = null;
try {
final ContentResolver contentResolver = getContentResolver();
res = contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
if (res != null && res.length > 0 && res[0] != null) {
newContactUri = res[0].uri;
Log.d(CallActivity.class.getName(), "URI added contact:"+ newContactUri);
Toast.makeText(this, "Successfully added " + displayName, Toast.LENGTH_LONG).show();
}
else Log.e(CallActivity.class.getName(), "Contact not added.");
} catch (NullPointerException | RemoteException | OperationApplicationException e) {
Log.e(CallActivity.class.getName(), e.getMessage(), e);
}
}

Update contact image in android contact provider

I create an Application to Read, Update, Delete Contacts Details.
Here is a problem to updating Contact_Image.
When new contact Added by device outside the Application without image.
then we can't update contact Image.
My Updating Code is.
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(Data.CONTACT_ID+"= ? AND "+ContactsContract.Data.MIMETYPE+"=?",new String[]{id,ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE})
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, imageInByte)
.build());
Please provide Solution Regard this.
You will have different code for updating a photo then adding a photo to a contact that doesn't have one. From your description above I believe you are trying to insert an image and not update an image, but here is code for both:
if(hasPhoto(resolver, id) == true)
{
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " = " + id + " AND " + ContactsContract.Data.MIMETYPE + " =='" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = resolver.query(ContactsContract.Data.CONTENT_URI, null, where, null, null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if (cursor.moveToFirst()) {
photoRow = cursor.getInt(idIdx);
}
cursor.close();
// Update current photo
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data._ID + " = ?", new String[] {Integer.toString(photoRow)})
.withValue(ContactsContract.Data.RAW_CONTACT_ID, id)
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.Data.DATA15, photoBytes)
.build());
try {
resolver.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
// Create new photo entry
int rawContactId = -1;
Cursor cursor = resolver.query(ContactsContract.RawContacts.CONTENT_URI, null, ContactsContract.RawContacts.CONTACT_ID + "=?", new String[] {id}, null);
if(cursor.moveToFirst())
{
rawContactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.RawContacts._ID));
if(rawContactId > -1)
{
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photoBytes)
.build());
try
{
resolver.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The difference being that if you are updating an existing photo you use the newUpdate function, but if you are inserting a photo to a contact that never had one you use newInsert

Add contact inside a group with group id

I need to insert a contact inside a group. I have the id of the group. But I can't. Don't know why.
Can anyone help me?
Here is my code.
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Account[] accounts = AccountManager.get(getActivity()).getAccounts();
String accountName = null;
String accountType = null;
String account = "mail#gmail.com";
for(Account account2 : accounts)
if(account2.name.equals(account)){
accountName = account2.name;
accountType = account2.type;
}
ops.add(ContentProviderOperation
.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName)
.build());
ops.add(ContentProviderOperation
.newAssertQuery(ContactsContract.Groups.CONTENT_URI)
.withSelection(ContactsContract.Groups._ID + "=?", new String[]{Long.toString(idGroup)})
.withExpectedCount(1)
.build());
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.CommonDataKinds.StructuredName.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "RICARDO")
.build());
try{
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}catch(Exception e){
Log.e("ERROR", e.toString());
}
This inserts a contact to a group by referring its id:
Builder builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
builder.withValueBackReference(Data.RAW_CONTACT_ID, 0);
builder.withValue(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
builder.withValue(GroupMembership.GROUP_ROW_ID, groupId);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(builder.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.e("ContactsManager", "Failed to apply batch: "+e);
}

Method returns java.lang.IllegalArgumentException?

I'm trying to insert the contacts with their content uri Contacts.CONTENT_URI
I just declaring the following code for inserting the valuse : -
public void runContact()
{
Uri u = Contacts.CONTENT_URI;
ContentValues initialValues = new ContentValues();
initialValues.put("data1", "1234567890");
initialValues.put("data2", "Emergency");
initialValues.put("data3", "Number");
cr.query(u, null, null, null, null);
Cursor cursor1 = getContentResolver().query(u, null, null, null, null);
if (cursor1.moveToFirst())
{
do {
if((cursor1.getString(cursor1.getColumnIndex("address"))).equalsIgnoreCase("9953834074111"))
{
String data1 = cursor1.getString(cursor1.getColumnIndex("data1"));
String data2 = cursor1.getString(cursor1.getColumnIndex("data2"));
String data3 = cursor1.getString(cursor.getColumnIndex("data3"));
Log.v("data1",data1);
Log.v("data2",data2);
Log.v("data3", data3);
}
} while (cursor1.moveToNext());
}
}
Whenever i called this method, it returns an exception like this -
java.lang.IllegalArgumentException: URI: content://contacts, calling user: com.android.data, calling package:com.android.data
Why this happened? What i'm doing wrong in that code? Anyone guide me?
Try like below code:
private void addContacts(){
try
{
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (c != null) {
while (c.moveToNext()) {
if (c.getString(c.getColumnIndex(Phone.DISPLAY_NAME)).equalsIgnoreCase(officeText.getText().toString())) {
Log.d("ContactUSActivity", "Number Exist");
Toast.makeText(ContactUsActivity_2_0.this,getResources().getString(R.string.contact_already_exist),Toast.LENGTH_SHORT).show();
return;
}
}
}
ArrayList<ContentProviderOperation> contentProviderArray = new ArrayList<ContentProviderOperation>();
Builder builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
builder.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE,null);
builder.withValue(ContactsContract.RawContacts.ACCOUNT_NAME,null);
ContentProviderOperation contentProvider = builder.build();
contentProviderArray.add(contentProvider);
contentProviderArray.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,0)
.withValue(ContactsContract.Data.MIMETYPE,StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, officeText.getText().toString())
.build());
contentProviderArray.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,0)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_MOBILE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneText.getText().toString())
.build());
contentProviderArray.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,addressText.getText().toString())
.build());
/*contentProviderArray.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.,addressText.getText().toString())
.build()); */
getContentResolver().applyBatch(ContactsContract.AUTHORITY, contentProviderArray);
Toast.makeText(ContactUsActivity_2_0.this,getResources().getString(R.string.contact_added),Toast.LENGTH_SHORT).show();
}
catch (OperationApplicationException e) {
Toast.makeText(ContactUsActivity_2_0.this,getResources().getString(R.string.contact_failed_to_added),Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
Toast.makeText(ContactUsActivity_2_0.this,getResources().getString(R.string.contact_failed_to_added),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}

Categories

Resources