Aggregate Contacts are added automatically? - android

you must have seen this piece of code somewhere else too,but obviously there's no answer for this exception.
EDIT: IF You've come here finding a solution to restoring contacts via vcardio.This is IT!!
I got this while utilising the vCardIO api for android used to restore contacts from vcard to the contacts db.I have been using the following doImport() method which is supposed to work just fine,but it isnt!
public void doImport(final String fileName, final boolean replace) {
try {
File vcfFile = new File(fileName);
final BufferedReader vcfBuffer = new BufferedReader(new FileReader(fileName),1048576);
final long maxlen = vcfFile.length();
// Start lengthy operation in a background thread
long importStatus = 0;
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
SQLiteStatement querySyncId = db.compileStatement("SELECT " + SYNCID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + PERSONID + "=?");
SQLiteStatement queryPersonId = db.compileStatement("SELECT " + PERSONID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + SYNCID + "=?");
SQLiteStatement insertSyncId = db.compileStatement("INSERT INTO " + SYNCDATA_TABLE_NAME + " (" + PERSONID + "," + SYNCID + ") VALUES (?,?)");
db.close();
Contact parseContact = new Contact(querySyncId, queryPersonId, insertSyncId);
String popa="";
popa=parseContact.getContent();
try {
long ret = 0;
do {
ret = parseContact.parseVCard(vcfBuffer);
//this is the snippet line which has the potential to beat the blues out of any programmer,always throwing an exception!
parseContact.addContact(CO, 0, true);
} while (ret > 0);
db.close();
} catch (Exception e) {
Toast.makeText(CO,"NO "+e.getMessage()+"-"+e.getLocalizedMessage()+"-"+e.toString(), Toast.LENGTH_SHORT).show();
}

Thanks,but no thanks.I managed it myself,Alhumdulillah.Make the following changes to
doImport();
Method of VCardIO:
public void doImport(final String fileName, final boolean replace) {
try {
File vcfFile = new File(fileName);
final BufferedReader vcfBuffer = new BufferedReader(new FileReader(fileName),1048576);
final long maxlen = vcfFile.length();
long importStatus = 0;
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
SQLiteStatement querySyncId = db.compileStatement("SELECT " + SYNCID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + PERSONID + "=?");
SQLiteStatement queryPersonId = db.compileStatement("SELECT " + PERSONID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + SYNCID + "=?");
SQLiteStatement insertSyncId = db.compileStatement("INSERT INTO " + SYNCDATA_TABLE_NAME + " (" + PERSONID + "," + SYNCID + ") VALUES (?,?)");
db.close();
Contact parseContact = new Contact(querySyncId, queryPersonId, insertSyncId);
String popa="";
popa=parseContact.getContent();
try {
long ret = 0;
do {
ret = parseContact.parseVCard(vcfBuffer);
/* GOOGLE CODE IS JUST THIS ON LINE WHICH AIN'T WORKING!!
parseContact.addContact(CO, 0, true); */
if (ret >= 0) {
String DisplayName = parseContact.displayName;
List<RowData> MobileNumbers=parseContact.phones;
List <RowData> Addresses = parseContact.addrs;
List <RowData> IMs = parseContact.ims;
List <OrgData> Orgs = parseContact.orgs;
String Notes = parseContact.notes;
byte[] dp = parseContact.photo;
String BirthDay = parseContact.birthday;
ContentResolver cr = CO.getContentResolver();
List<RowData> mails=parseContact.emails;
try
{
// ADDING NAME
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, DisplayName) // Name of the person
.build());
//ADDING PHONES
for(RowData l : MobileNumbers)
{
{
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER,l.data)
.withValue(Phone.TYPE,l.type).build());
}
}
//ADDING MAILS
for(RowData a :mails)
{
{
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
.withValue(Email.DATA,a.data)
.withValue(Email.TYPE, a.type).build());
}
}
//ADDING ADDRESSES
for(RowData add :Addresses)
{
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(StructuredPostal.DATA,add.data)
.withValue(StructuredPostal.TYPE, add.type).build());
}
//ADDING ORGANISATIONS
for(OrgData org :Orgs)
{
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,Organization.CONTENT_ITEM_TYPE)
.withValue(Organization.DATA,org.company)
.withValue(Organization.TYPE, org.type)
.withValue(Organization.TITLE, org.title)
.withValue(Organization.LABEL, org.customLabel)
.build());
}
//ADDING IMs
for(RowData IM :IMs)
{
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,Im.CONTENT_ITEM_TYPE)
.withValue(Im.DATA,IM.data)
.withValue(Im.TYPE, IM.type).build());
}
//ADDING NOTES
if(Notes!=null && !Notes.equals(""))
{
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,Note.CONTENT_ITEM_TYPE)
.withValue(Note.NOTE,Notes).build());
}
// ADDING PHOTO
if(dp!=null)
{
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,Photo.CONTENT_ITEM_TYPE)
.withValue(Photo.PHOTO,dp).build());
}
//ADDING BIRTHDAY
if(BirthDay!=null && !BirthDay.equals(""))
{
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,CommonDataKinds.Event.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.Event.START_DATE,BirthDay)
.withValue(CommonDataKinds.Event.TYPE,CommonDataKinds.Event.TYPE_BIRTHDAY).build()); // Number of the person
}
cr.applyBatch(ContactsContract.AUTHORITY, ops);
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(CO, "Exception: "+e.toString()+"Eebolra:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
importStatus += parseContact.getParseLen();
}
db.close();
} while (ret > 0);
db.close();
} catch (Exception e) {
Toast.makeText(CO,"NO "+e.getMessage()+"-"+e.getLocalizedMessage()+"-"+e.toString(), Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
}
}

Related

Android - Update contacts without using Intent

Please help me, I am trying to update a contact by CONTACT_ID or by NAME. The only way i got it to work is with using Intent, but I want it to be updated in the background thread.
These are the code snippets I tried:
try {
String newName = "test";
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
ContactsContract.Contacts.Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
new String[]{"Alexa Prg"})
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, newName)
.build());
ContentProviderResult[] result = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
// Do Any thing
}
and
Activity context = new Activity();
try {
ContentResolver contentResolver = context.getContentResolver();
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<>();
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
ContactsContract.Contacts.Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
new String[]{"560"}) //ID
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, newName)
.build());
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
}
Both the snippets aren't working

Android : Update exicting Contact List

I am trying to edit my contact list through my App. I can able to update Contact name , Phone number and Email. But, when I try to change existing photo it is not updating.
When I try to add new contact with image it is successfully added
Problem occur when I try to edit existing Contact with Image
Code that I using for Update Contact
ContentResolver contentResolver = getContentResolver();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] emailParams = new String[]{idValue, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE};
String[] nameParams = new String[]{idValue, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
String[] numberParams = new String[]{idValue, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
int photoRow = -1;
String wherePhoto = ContactsContract.Data.RAW_CONTACT_ID + " = " + idValue + " AND " + ContactsContract.Data.MIMETYPE + " =='" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = contentResolver.query(ContactsContract.Data.CONTENT_URI, null, wherePhoto, null, null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if (cursor.moveToFirst()) {
photoRow = cursor.getInt(idIdx);
}
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<android.content.ContentProviderOperation>();
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,emailParams)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, edt_contactEmail.getText().toString().trim())
.build());
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,nameParams)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, edt_contact_name.getText().toString().trim())
.build());
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,numberParams)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, edt_contactNumber.getText().toString().trim())
.build());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if(contact_bitmap!=null){ // If an image is selected successfully
contact_bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
byte[] b = stream.toByteArray();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data._ID + " = ?", new String[]{Integer.toString(photoRow)})
.withValue(ContactsContract.Data.RAW_CONTACT_ID, idValue)
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.Data.DATA15, b)
.build());
try {
stream.flush();
}catch (IOException e) {
e.printStackTrace();
}
}
try {
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(EditContacts.this,"Contact Successfully updated",Toast.LENGTH_LONG).show();
Intent i = new Intent(EditContacts.this,MainActivity.class);
finish();
startActivity(i);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
Can any one please tell me how to edit existing contact with image.
Thanks in advance :)
I have used this example for updating contact.
ContactManager
Method to update Contact:
boolean updateContact(String contactID, String contactName, String contactNumber, String contactEmailAdd, Bitmap bitmap) {
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
+ "=?", new String[]{contactID, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE})
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contactName)
.build());
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
+ "=? AND " + ContactsContract.CommonDataKinds.Organization.TYPE + "=?"
, new String[]{contactID, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
, String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)})
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contactNumber)
.build());
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
+ "=? AND " + ContactsContract.CommonDataKinds.Organization.TYPE + "=?"
, new String[]{contactID, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
, String.valueOf(Email.TYPE_WORK)})
.withValue(Email.ADDRESS, contactEmailAdd)
.build());
try {
ByteArrayOutputStream image = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, image);
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?", new String[]{contactID, Photo.CONTENT_ITEM_TYPE})
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(Photo.PHOTO, image.toByteArray())
.build());
/*Builder builder;
builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
builder.withSelection(ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[]{contactID, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE});
builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, image.toByteArray());
ops.add(builder.build());*/
} catch (Exception e) {
e.printStackTrace();
}
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

Why can not I set the email address if not set before the name to android?

I can not understand why I can not enter the email address unless you first insert the name , if the comment section what set the name the email works fine but I can not rightly then to enter the name , can anyone help ?
public String updateContact(String id, String name, String number,
String email, String surname, Context context,
ArrayList<EmailContactBean> listEmail) {
String resultId = null;
if (id == null) {
resultId = addContact(context, name, surname, number, email);
} else {
String raw_contact_id = getRawContactId(id, context);
ContentResolver contentResolver = context.getContentResolver();
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
// update name
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=?",
new String[] { id })
.withValue(StructuredName.GIVEN_NAME, name).build());
// update surname
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(COLUMN_CONTACT_ID + "=? ",
new String[] { id })
.withValue(StructuredName.DATA3, surname).build());
// update number
Cursor numberCur = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[] { id }, null);
if ((null == numberCur) || (!numberCur.moveToFirst())) {
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID,
raw_contact_id)
.withValue(ContactsContract.Data.MIMETYPE,
Phone.CONTENT_ITEM_TYPE)
.withValue(
ContactsContract.CommonDataKinds.Phone.NUMBER,
number).build());
} else {
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
COLUMN_CONTACT_ID + "=? AND " + COLUMN_MIMETYPE
+ "=?",
new String[] { id, MIMETYPE_STRING_PHONE })
.withValue(COLUMN_NUMBER, number)
.build());
}
// update email
Cursor emailCur = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[] { id }, null);
if ((null == emailCur) || (!emailCur.moveToFirst())) {
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID,
raw_contact_id)
.withValue(ContactsContract.Data.MIMETYPE,
Email.CONTENT_ITEM_TYPE)
.withValue(Email.TYPE, listEmail.get(0).getType())
.withValue(ContactsContract.CommonDataKinds.Email.DATA,
listEmail.get(0).getName()).build());
} else {
for (int i = 0; i < listEmail.size(); i++) {
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
ContactsContract.Data._ID + "=? AND "
+ COLUMN_MIMETYPE + "=?",
new String[] { listEmail.get(i).getId(),
MIMETYPE_STRING_EMAIL })
.withValue(COLUMN_EMAIL, listEmail.get(i).getName())
.withValue(COLUMN_EMAIL_TYPE,
listEmail.get(i).getType()).build());
}
}
try {
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
}
}
return resultId;
}
I solved it , just do not set MIMETYPE 's name and surname :
// update name
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
ContactsContract.Data.CONTACT_ID + "=? AND "
+ COLUMN_MIMETYPE + "=?",
new String[] { id, MIMETYPE_STRING_NAME })
.withValue(StructuredName.DATA2, name).build());
// update surname
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
COLUMN_CONTACT_ID + "=? AND " + COLUMN_MIMETYPE
+ "=?",
new String[] { id, MIMETYPE_STRING_NAME })
.withValue(StructuredName.DATA3, surname).build());

Modify contacts not working ( java.lang.NullPointerException )

I have a problem with editing contacts in Android. I'm using contentProviderOperation with newUpdate, but it's not working. It only works when the field already has something. If I have a field filled, erase it, then save and try to edit it again, I find that it's not saved and that's when I get the exception.
Here is the code I have to edit:
if (emailantigo.equals("") && !email.equals("")) {
debug("email " + email);
debug("id " + contactId);
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.RawContacts.CONTACT_ID, contactId)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.withValue(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS,
email).build());
} else if (!email.equals(emailantigo)) {
debug("email " + email);
debug("id " + contactId);
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
ContactsContract.RawContacts.CONTACT_ID
+ "=? AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
+ "'",
new String[] { String.valueOf(contactId) })
.withValue(ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.withValue(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS,
email).build());
}
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
public void debug(String msg) {
Log.i("CONTATOS", msg);
}
Here is the exception I get, from LogCat:
java.lang.NullPointerException
android.os.Parcel.readException(Parcel.java:1266)
android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:160)
android.database.DatabaseUtils.readExceptionWithOperationApplicationExceptionFromParcel(DatabaseUtils.java:137)
android.content.ContentProviderProxy.applyBatch(ContentProviderNative.java:460)
android.content.ContentProviderClient.applyBatch(ContentProviderClient.java:95)
android.content.ContentResolver.applyBatch(ContentResolver.java:622)
** EDIT 2 **
found solution by myself
the partial code that works:
Cursor cursorEmail = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = "
+ contactId, null, null);
if (cursorEmail.moveToFirst()) {
if (!email.equals(emailantigo))
key_email = ops
.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
ContactsContract.Data.CONTACT_ID
+ "=? AND "
+ ContactsContract.Data.MIMETYPE
+ "=? AND "
+ ContactsContract.CommonDataKinds.Email.TYPE
+ "=?",
new String[] {
String.valueOf(contactId),
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_WORK) })
.withValue(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(
ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.withValue(
ContactsContract.CommonDataKinds.Email.ADDRESS,
email).build());
}
cursorEmail.close();
if (!key_email && emailantigo.equals("") && !email.equals(emailantigo)) {
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID,
String.valueOf(contactId))
.withValue(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS,
email)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.build());
}
the newInsert not works with Data._ID or Data.Contact_ID, I dont know why, must have some logic behind this, but its working now ^^ !
Obs: Not tested in synced contacts.

adding custom type of number to a contact [Android]

I been working on an app that helps sending sms to your contacts. Everything is great, except that I'm supposed to add a "custom field number" to a contact such as "Work" or "Private". I'd search the web for answers and the ones that are useful for evryone, aren't for me. This is my code:
private void AddCtxtAttribute(int contactID, String contactNumber) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(Data.CONTENT_URI);
builder.withValue(Data.RAW_CONTACT_ID, contactID);
builder.withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.Data.DATA1, contactNumber);
builder.withValue(ContactsContract.Data.DATA2, Phone.TYPE_CUSTOM);
builder.withValue(ContactsContract.Data.DATA3, "My Custom Label");
ops.add(builder.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Log.e("RESULT", "Success! " + contactID + " - "
+ contactNumber);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ERROR", "error : " + e.toString());
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ERROR", "error : " + e.toString());
}
}
And it's called:
AddCtxtAttribute(contacto_id, contacto_numero);
where contacto_id and contacto_numero are a int and a String respectively.
The problem is that when I pressed the button, I have the ID (contacto_id) of that contact but it updates other contact. (like the id's don't match) but i've debug it and the id doesn't change.
Can anyone help me with this?
I figured it out!
the problem was that i was using diferent column names and uris in reading the contacts and inserting a new contact number.
I did this:
to query all contacts:
private void llenar_contactos() {
ProgressDialog progress;
lista_contactos_cel_sobrantes = null;
sobrantes = false;
lista_contactos_cel = new ArrayList<HashMap<String, Object>>();
progress = ProgressDialog.show(contactsActivity.this, "",
"Cargando Contactos. Porfavor espere...");
String[] projection = new String[] { Data.RAW_CONTACT_ID,
Phone.DISPLAY_NAME, Phone.NUMBER, Phone.LABEL };
String selection = Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'";
// ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "='1'";
String sort_order = "display_name ASC";
Uri mContacts = Data.CONTENT_URI;
// ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor contacts = getContentResolver().query(mContacts, // Contact URI
projection, // Which columns to return
selection, // Which rows to return
null, // Where clause parameters
sort_order // Order by clause
);
total_contactos = contacts.getCount();
if (total_contactos > 0) {
int i = 0;
int multiplo = 0;
int indice_total = 0;
int temp_registros = 0;
String contact_id = "";
String name = "";
String phoneNo = "";
String label = "";
sobrantes = false;
int nameFieldColumnIndex = 0;
while (contacts.moveToNext()) {
nameFieldColumnIndex = contacts.getColumnIndex(Data.RAW_CONTACT_ID);
if (nameFieldColumnIndex > -1) {
contact_id = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.DISPLAY_NAME);
if (nameFieldColumnIndex > -1) {
name = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.NUMBER);
if (nameFieldColumnIndex > -1) {
phoneNo = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.LABEL);
if (nameFieldColumnIndex > -1) {
label = contacts.getString(nameFieldColumnIndex);
}
if(label != null){
Log.i("CONTACTO", "id: " + contact_id + " -> name: " + name
+ " ->number: " + phoneNo + " ->label: " + label);
} else {
Log.d("CONTACTO", "id: " + contact_id + " -> name: " + name
+ " ->number: " + phoneNo + " ->label: " + label);
}
}
contacts.close();
}
}
And to insert a new custom label:
private void AddCtxtAttribute(int contactID, String contactNumber) {
if (contactID != 0 && contactNumber != null) {
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValue(Data.RAW_CONTACT_ID, contactID)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, contactNumber)
.withValue(Phone.TYPE, Phone.TYPE_CUSTOM)
.withValue(Phone.LABEL, "My Custom Label")
.build());
try{
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories

Resources