Android插入联系人未显示名称

时间:2015-11-30 05:11:13

标签: android android-intent android-contacts

我正在尝试将联系人从我的应用程序导出到Android的默认联系人列表。我正在使用意图通过启动联系活动来插入联系人详细信息。联系活动预先填充表单中的大多数意图数据,但无法填充联系人的姓名。这是我填充意图数据的代码。

ArrayList<ContentValues> data = new ArrayList<>();

        if (!contactDetails.getName().isEmpty()) {
            ContentValues rowName = new ContentValues();
            rowName.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
            rowName.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contactDetails.getName());
            data.add(rowName);
        }
        if (!contactDetails.getCompany().isEmpty()) {
            ContentValues rowCompany = new ContentValues();
            rowCompany.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
            rowCompany.put(ContactsContract.CommonDataKinds.Organization.COMPANY, contactDetails.getCompany());
            data.add(rowCompany);

        }

        if (!contactDetails.getPhone().isEmpty()) {
            ContentValues rowPhone = new ContentValues();
            rowPhone.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            rowPhone.put(ContactsContract.CommonDataKinds.Phone.NUMBER, contactDetails.getPhone());
            data.add(rowPhone);
        }

        ContentValues rowEmail = new ContentValues();
        rowEmail.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
        rowEmail.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_MOBILE);
        rowEmail.put(ContactsContract.CommonDataKinds.Email.LABEL, "Work");
        rowEmail.put(ContactsContract.CommonDataKinds.Email.ADDRESS, contactDetails.getEmail());
        data.add(rowEmail);

        Intent intent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);
        intent.putParcelableArrayListExtra(ContactsContract.Intents.Insert.DATA, data);

        startActivity(intent);

这是屏幕截图。请注意,即使intent有数据,name字段也是空的。

Contact insert activity

我觉得我没有为以下几行提供正确的价值。

rowName.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                rowName.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contactDetails.getName());

我尝试了NickName字段,它确实有效。示例代码。

if (!contactDetails.getName().isEmpty()) {
            ContentValues rowName = new ContentValues();
            rowName.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE);
            rowName.put(ContactsContract.CommonDataKinds.Nickname.NAME, contactDetails.getName());
            data.add(rowName);
        }

但不确定为什么它无法成功显示名称。我在这里错过了什么吗?

3 个答案:

答案 0 :(得分:1)

试试这个对我有用,如果你还面临任何问题,请告诉我。这里有五个字段供用户插入数据,你可以根据需要修改它。

这是添加新联系人

   // Creating a button click listener for the "Add Contact" button
    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_phone);

            // Getting reference to HomePhone EditText 
            EditText etHomePhone = (EditText) findViewById(R.id.et_home_phone);

            // Getting reference to HomeEmail EditText 
            EditText etHomeEmail = (EditText) findViewById(R.id.et_home_email);

            // Getting reference to WorkEmail EditText 
            EditText etWorkEmail = (EditText) findViewById(R.id.et_work_email);             

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

            // Adding insert operation to operations list
            // to  insert Home Phone 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, etHomePhone.getText().toString())
                    .withValue(Phone.TYPE, Phone.TYPE_HOME)
                    .build());

            // Adding insert operation to operations list
            // to insert Home Email in the table ContactsContract.Data
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
                    .withValue(ContactsContract.Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
                    .withValue(Email.ADDRESS, etHomeEmail.getText().toString())
                    .withValue(Email.TYPE, Email.TYPE_HOME)
                    .build());

            // Adding insert operation to operations list
            // to insert Work Email in the table ContactsContract.Data
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
                    .withValue(ContactsContract.Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
                    .withValue(Email.ADDRESS, etWorkEmail.getText().toString())
                    .withValue(Email.TYPE, Email.TYPE_WORK)
                    .build());              

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

这是用于显示联系人列表

OnClickListener contactsClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Creating an intent to open Android's Contacts List
            Intent contacts = new Intent(Intent.ACTION_VIEW,ContactsContract.Contacts.CONTENT_URI);

            // Starting the activity
            startActivity(contacts);                
        }
    };

这是您需要在清单

中设置的权限
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>

答案 1 :(得分:1)

我通过在startActivity()方法调用之前添加以下行来解决此问题。

intent.putExtra(ContactsContract.Intents.Insert.NAME, contactDetails.getName());

答案 2 :(得分:0)

您可以使用游标从设备获取联系人。

public void fetchContacts() {

    String phoneNumber = null;
    String email = null;

    Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
    String _ID = ContactsContract.Contacts._ID;
    String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
    String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

    Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
    String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;

    Uri EmailCONTENT_URI =  ContactsContract.CommonDataKinds.Email.CONTENT_URI;
    String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
    String DATA = ContactsContract.CommonDataKinds.Email.DATA;

    StringBuffer output = new StringBuffer();

    ContentResolver contentResolver = getContentResolver();

    Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);  

    // Loop for every contact in the phone
    if (cursor.getCount() > 0) {

        while (cursor.moveToNext()) {

            String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
            String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));

            int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));

            if (hasPhoneNumber > 0) {

                output.append("\n First Name:" + name);

                // Query and loop for every phone number of the contact
                Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);

                while (phoneCursor.moveToNext()) {
                    phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                    output.append("\n Phone number:" + phoneNumber);

                }

                phoneCursor.close();

                // Query and loop for every email of the contact
                Cursor emailCursor = contentResolver.query(EmailCONTENT_URI,    null, EmailCONTACT_ID+ " = ?", new String[] { contact_id }, null);

                while (emailCursor.moveToNext()) {

                    email = emailCursor.getString(emailCursor.getColumnIndex(DATA));

                    output.append("\nEmail:" + email);

                }

                emailCursor.close();
            }

            output.append("\n");
        }

         System.out.println(output);
    }
}