Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

Inserting contacts in Android 2.2

I am trying to insert new RawContact contacts, but the RawContact added doesn't get displayed when I view the contacts through Contacts or phonebook. As I understand if we create a RawContact and there is no contact associated with it then the contact will be automatically inserted. I get a valid value of rawContactId and no exceptions are thrown, so I assume the insertion is successful. Am I doing anything wrong or am I missing something? I am using the code example from developer site, just pasting it here:

 ContentValues values = new ContentValues();
 values.put(RawContacts.ACCOUNT_TYPE, accountType); 
 values.put(RawContacts.ACCOUNT_NAME, accountName);
 Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values); 
 long rawContactId = ContentUris.parseId(rawContactUri); 

 values.clear(); 
 values.put(Data.RAW_CONTACT_ID, rawContactId); 
 values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); 
 values.put(StructuredName.DISPLAY_NAME, "Mike Sullivan"); 
 getContentResolver().insert(Data.CONTENT_URI, values); 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I thought this Q was long forgotten but Since someone upvoted it, I am assuming someone else also faces the same problem as me. After a little struggle I was able to figure out the problem and insert contacts, Hope this helps, here is the sample code:

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(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE)
   .withValue(Phone.NUMBER, "9X-XXXXXXXXX")
   .build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
   .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
   .withValue(Data.MIMETYPE,StructuredName.CONTENT_ITEM_TYPE)
   .withValue(StructuredName.DISPLAY_NAME, "Mike Sullivan")
   .build());  
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...