2011-01-20 70 views
59

我已經寫了下面的代碼來添加新的聯繫人在android電話簿,它工作,但是當我打開聯繫人菜單,我看不到添加的新聯繫人。任何人都可以幫我找出這裏有什麼問題嗎?如何在android中添加新的聯繫人

import android.app.Activity; 
import android.os.Bundle; 

import android.content.ContentResolver; 
import android.content.ContentValues; 
import android.provider.ContactsContract; 

import android.widget.TextView; 
import android.widget.Toast; 

public class AddContacts extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     try { 
      ContentResolver cr = this.getContentResolver(); 
      ContentValues cv = new ContentValues(); 
      cv.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, "New Name"); 
      cv.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "1234567890"); 
      cv.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE); 
      cr.insert(ContactsContract.RawContacts.CONTENT_URI, cv); 

      Toast.makeText(this, "Contact added", Toast.LENGTH_LONG).show(); 
     } catch(Exception e) { 
      TextView tv = new TextView(this); 
      tv.setText(e.toString()); 
      setContentView(tv); 
     } 
    } 
} 
+1

此鏈接可usefuk到u http://saigeethamn.blogspot.com/2009/09/android-developer-tutorial-part-10.html – 2011-01-20 07:15:42

+0

感謝üParag Saigeethamn的博客也很有幫助 – 2011-01-20 10:42:53

+0

但對於舊版本的Android – 2011-01-20 10:53:14

回答

19

這是對我工作的罰款:

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(Data.CONTENT_URI) 
        .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex) 
        .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE) 
        .withValue(StructuredName.DISPLAY_NAME, "Vikas Patidar") // Name of the person 
        .build()); 
      ops.add(ContentProviderOperation 
        .newInsert(Data.CONTENT_URI) 
        .withValueBackReference(
          ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex) 
        .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE) 
        .withValue(Phone.NUMBER, "9999999999") // Number of the person 
        .withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); // Type of mobile number      
      try 
      { 
       ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); 
      } 
      catch (RemoteException e) 
      { 
       // error 
      } 
      catch (OperationApplicationException e) 
      { 
       // error 
      }  
162

我在這裏張貼了一段代碼,我用它來添加新的聯繫人。這對我來說可以。我希望它能幫助你。

String DisplayName = "XYZ"; 
String MobileNumber = "123456"; 
String HomeNumber = "1111"; 
String WorkNumber = "2222"; 
String emailID = "[email protected]"; 
String company = "bad"; 
String jobTitle = "abcd"; 

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()); 

//------------------------------------------------------ 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()); 
} 

//------------------------------------------------------ Mobile Number      
if (MobileNumber != null) { 
    ops.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.NUMBER, MobileNumber) 
     .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
    ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) 
     .build()); 
} 

//------------------------------------------------------ Home Numbers 
if (HomeNumber != null) { 
    ops.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.NUMBER, HomeNumber) 
     .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
    ContactsContract.CommonDataKinds.Phone.TYPE_HOME) 
     .build()); 
} 

//------------------------------------------------------ Work Numbers 
if (WorkNumber != null) { 
    ops.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.NUMBER, WorkNumber) 
     .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
    ContactsContract.CommonDataKinds.Phone.TYPE_WORK) 
     .build()); 
} 

//------------------------------------------------------ Email 
if (emailID != null) { 
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) 
     .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) 
     .withValue(ContactsContract.Data.MIMETYPE, 
    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE) 
     .withValue(ContactsContract.CommonDataKinds.Email.DATA, emailID) 
     .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK) 
     .build()); 
} 

//------------------------------------------------------ Organization 
if (!company.equals("") && !jobTitle.equals("")) { 
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) 
     .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) 
     .withValue(ContactsContract.Data.MIMETYPE, 
    ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE) 
     .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company) 
     .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK) 
     .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle) 
     .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK) 
     .build()); 
} 

// Asking the Contact provider to create a new contact     
try { 
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); 
} catch (Exception e) { 
    e.printStackTrace(); 
    Toast.makeText(myContext, "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
} 

這是代碼。根據您的需要進行整合。我希望這會有所幫助。

11

這些例子都很好,我想指出你可以使用Intent實現相同的結果。意圖打開聯繫人應用程序,其中包含您已提供的字段。

用戶可以保存新創建的聯繫人。

你可以閱讀一下: https://developer.android.com/training/contacts-provider/modify-data.html

Intent contactIntent = new Intent(ContactsContract.Intents.Insert.ACTION); 
contactIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE); 

contactIntent 
     .putExtra(ContactsContract.Intents.Insert.NAME, "Contact Name") 
     .putExtra(ContactsContract.Intents.Insert.PHONE, "5555555555"); 

startActivityForResult(contactIntent, 1); 

startActivityForResult()讓您有機會看到的結果。

我已經注意到了resultCode爲工作在> 5.0的設備,

,但我有一箇舊的三星(< 5)總是返回RESULT_CANCELLED(0)。

我明白這是默認返回,如果活動不期望返回任何東西。

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { 
    super.onActivityResult(requestCode, resultCode, intent); 

    if (requestCode == 1) 
    { 
     if (resultCode == Activity.RESULT_OK) { 
      Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show(); 
     } 
     if (resultCode == Activity.RESULT_CANCELED) { 
      Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 
2

這並不是說上述的答案是不正確的,但我覺得這個非常的代碼很容易理解,因此我與大家在這裏分享。並且還有對WRITE_CONTACTS權限的檢查。

以下是如何將電話號碼,電子郵件,網站等添加到現有聯繫人的完整代碼。

public static void addNumberToContact(Context context, Long contactRawId, String number) throws RemoteException, OperationApplicationException { 
    addInfoToAddressBookContact(
      context, 
      contactRawId, 
      ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, 
      ContactsContract.CommonDataKinds.Phone.NUMBER, 
      ContactsContract.CommonDataKinds.Phone.TYPE, 
      ContactsContract.CommonDataKinds.Phone.TYPE_OTHER, 
      number 
    ); 
} 

public static void addEmailToContact(Context context, Long contactRawId, String email) throws RemoteException, OperationApplicationException { 
    addInfoToAddressBookContact(
      context, 
      contactRawId, 
      ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, 
      ContactsContract.CommonDataKinds.Email.ADDRESS, 
      ContactsContract.CommonDataKinds.Email.TYPE, 
      ContactsContract.CommonDataKinds.Email.TYPE_OTHER, 
      email 
    ); 
} 

public static void addURLToContact(Context context, Long contactRawId, String url) throws RemoteException, OperationApplicationException { 
    addInfoToAddressBookContact(
      context, 
      contactRawId, 
      ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE, 
      ContactsContract.CommonDataKinds.Website.URL, 
      ContactsContract.CommonDataKinds.Website.TYPE, 
      ContactsContract.CommonDataKinds.Website.TYPE_OTHER, 
      url 
    ); 
} 

private static void addInfoToAddressBookContact(Context context, Long contactRawId, String mimeType, String whatToAdd, String typeKey, int type, String data) throws RemoteException, OperationApplicationException { 
    if(ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_DENIED) { 
     return; 
    } 
    ArrayList<ContentProviderOperation> ops = new ArrayList<>(); 
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) 
      .withValue(ContactsContract.Data.RAW_CONTACT_ID, contactRawId) 
      .withValue(ContactsContract.Data.MIMETYPE, mimeType) 
      .withValue(whatToAdd, data) 
      .withValue(typeKey, type) 
      .build()); 
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); 
} 
相關問題