如何通过Android手机联系人列表中的代码添加联系人详细信息..?

Posted

技术标签:

【中文标题】如何通过Android手机联系人列表中的代码添加联系人详细信息..?【英文标题】:how to add contact detail through code in contact list of Android Phone ..? 【发布时间】:2011-09-10 01:27:30 【问题描述】:

**我试过这段代码。它工作正常,没有任何错误。但是在createContact 方法之后,我打开了android 的联系人应用程序。我使用createContact 添加的联系人不存在。当我单击显示联系人时,它正在显示。

究竟是什么问题?**

如果您有其他代码,请发布...

import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.database.Cursor;

import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class NativeContentProvider extends Activity 


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nativecontentprovider);

        Button view = (Button)findViewById(R.id.viewButton);
        Button add = (Button)findViewById(R.id.createButton);
        Button modify = (Button)findViewById(R.id.updateButton);
        Button delete = (Button)findViewById(R.id.deleteButton);


        view.setOnClickListener(new OnClickListener() 
            public void onClick(View v)
                displayContacts();
                Log.i("NativeContentProvider", "Completed Displaying Contact list");
            
        );

        add.setOnClickListener(new OnClickListener() 
            public void onClick(View v)
                createContact("Mangesh Joshi", "123456789");
                Log.i("NativeContentProvider", "Created a new contact, of course hard-coded");
            
        );

        modify.setOnClickListener(new OnClickListener() 
            public void onClick(View v) 
                updateContact("Sample Name", "987654321");
                Log.i("NativeContentProvider", "Completed updating the email id, if applicable");
            
        );

        delete.setOnClickListener(new OnClickListener() 
            public void onClick(View v) 
                deleteContact("Sample Name");
                Log.i("NativeContentProvider", "Deleted the just created contact");
            
        );


private void displayContacts() 

    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);
    if (cur.getCount() > 0) 
        while (cur.moveToNext()) 
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(cur.getString(
                    cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) 
                 Cursor pCur = cr.query(
                         ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                         null, 
                         ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                         new String[]id, null);
                 while (pCur.moveToNext()) 
                     String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                     Toast.makeText(NativeContentProvider.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
                  
            pCur.close();
        
        
    


private void createContact(String name, String phone) 
    ContentResolver cr = getContentResolver();

    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

    if (cur.getCount() > 0) 
        while (cur.moveToNext()) 
            String existName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (existName.contains(name)) 
                Toast.makeText(NativeContentProvider.this,"The contact name: " + name + " already exists", Toast.LENGTH_SHORT).show();
                return;                 
            
        
    

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Contacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "accountname@gmail.com")
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "com.google")
            .build());

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Contacts.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, name)
            .build());

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Contacts.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
            .build());


    try 
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
     catch (RemoteException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
     catch (OperationApplicationException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
    

    Toast.makeText(NativeContentProvider.this, "Created a new contact with name: " + name + " and Phone No: " + phone, Toast.LENGTH_SHORT).show();



private void updateContact(String name, String phone) 
    ContentResolver cr = getContentResolver();

    String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " + 
                ContactsContract.Data.MIMETYPE + " = ? AND " +
                String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";
    String[] params = new String[] name,
            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
            String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME);

    Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI, null, where, params, null);

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    if ( (null == phoneCur)  ) 
        createContact(name, phone);
     else 
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(where, params)
                .withValue(ContactsContract.CommonDataKinds.Phone.DATA, phone)
                .build());
    

    phoneCur.close();

    try 
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
     catch (RemoteException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
     catch (OperationApplicationException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
    

    Toast.makeText(NativeContentProvider.this, "Updated the phone number of 'Sample Name' to: " + phone, Toast.LENGTH_SHORT).show();


private void deleteContact(String name) 

    ContentResolver cr = getContentResolver();
    String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
    String[] params = new String[] name;

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
            .withSelection(where, params)
            .build());
    try 
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
     catch (RemoteException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
     catch (OperationApplicationException e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
    

    Toast.makeText(NativeContentProvider.this, "Deleted the contact with name '" + name +"'", Toast.LENGTH_SHORT).show();



【问题讨论】:

【参考方案1】:
import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.os.Bundle;
import android.provider.ContactsContract;
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);
        
*/        
        String DisplayName = "XYZ";
        String MobileNumber = "123456";
        String HomeNumber = "1111";
        String WorkNumber = "2222";
        String emailID = "email@nomail.com";
        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(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                           



    

【讨论】:

【参考方案2】:

确保您已启用联系人列表的显示选项。联系人列表>菜单选项>显示选项>在您的帐户上打勾

【讨论】:

【参考方案3】:
    insertContact(getContentResolver(),editTextName.getText().toString(),editTextPhone.getText().toString());
    //if (checkBoxSelf.isChecked())
      //  Toast.makeText(getApplicationContext(), "Self", Toast.LENGTH_SHORT).show();
   // else 
    //    Toast.makeText(getApplicationContext(), "Other", Toast.LENGTH_SHORT).show();
    //

    // Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(this, AllCardsActivity.class);
    startActivity(intent);

    //hideProgressBar();
    finish();


public static boolean insertContact(ContentResolver contentResolver,String firstName, String mobileNumber) 
    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());

    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.GIVEN_NAME,firstName).build());

    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());
    try 
        contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
     catch (Exception e) 
        return false;
    
    return true;

// 工作代码只需要获得app的权限

【讨论】:

以上是关于如何通过Android手机联系人列表中的代码添加联系人详细信息..?的主要内容,如果未能解决你的问题,请参考以下文章

如何通过长按我的 Android 应用程序的联系人列表中的联系人添加附加选项?

如何通过 Node JS 使用自己的库将联系人添加到 Mailchimp 中的列表/受众

如何使用 Android 将手机联系人照片的总列表上传到服务器?

如何使用 ListView 删除 Android Studio 显示中的重复联系人 [重复]

如何在android中以编程方式显示联系人列表?

如何在没有任何服务器端代码的情况下借助 HTML 在 android 和 iphone 中添加新的联系人屏幕?