我无法使用内容提供商在Android应用程序中更新我的电子邮件

时间:2012-10-09 04:18:32

标签: android android-contentprovider

我正在处理检索所有Android联系人的应用程序,也可以删除和更新联系人。所有工作正常的问题是当联系人没有电子邮件地址然后我无法使用我的应用程序更新它(无法添加电子邮件地址从我的更新联系页面)。我在下面写了用过的代码。提前谢谢。

private void updateEmaill(String id, String email) {

    ContentResolver cr = getContentResolver();

    String where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND "
            + ContactsContract.Data.MIMETYPE + " = ?";

    String[] params = new String[] { id,
            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE };

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

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

    if ((null == phoneCur)) {


        System.out.println("we have got null value from the cursor");

    } else {



        System.out.println("phone cursor count" + phoneCur.getCount());





        ops.add(ContentProviderOperation
                .newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(where, params)
                .withValue(ContactsContract.CommonDataKinds.Email.ADDRESS,
                        email).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();
    }

}

1 个答案:

答案 0 :(得分:0)

已知

newUpdate()仅在已存在给定字段时才起作用。

作为一种解决方法,这里有一个简单的逻辑:

  -check if email exists for contacts
  -if it does call update
  -if it doesn't save all the fields of this contact in some variables and delete the  contact
  -use newInsert() to create a new contact with the saved fields from old contact and also the email that you need to add.