【问题标题】:Android content provider returning wrong contact idAndroid 内容提供商返回错误的联系人 ID
【发布时间】:2019-06-28 05:50:57
【问题描述】:

我正在开发一个管理联系人(添加、更新、删除)的 Android 应用程序

这是在列表视图中列出联系人的代码

list_ct.clear();
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor != null)
{
    while (cursor.moveToNext())
    {
        String id = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
        String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        Cursor cursor2 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
        ArrayList<String> phones = new ArrayList<String>();
        while (cursor2.moveToNext())
        {
            String phoneNumber = cursor2.getString(cursor2.getColumnIndex(CommonDataKinds.Phone.NUMBER));
            phones.add(phoneNumber);
        }
        Contact ct = new Contact(id,name,phones);
        adapter.notifyDataSetChanged();
    }
}

这是列表视图事件监听器

lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        Contact current = (Contact)list_ct.get(position);
        Intent in=new Intent(Intent.ACTION_EDIT,Uri.parse("content://contacts/people/"+current.getId()));
        startActivityForResult(in,2);
    }
});

当我单击列表视图中的联系人时,其中一些人的意图会立即打开和关闭,就好像该 id 不存在于联系人的数据库中一样,而对于其他人,它会打开另一个联系人的联系人编辑。

联系人显示名称及其电话号码显示正确,但 ID 错误。我不明白为什么第一个光标中的 id 用于显示联系人的电话号码,但不能用于更新。

【问题讨论】:

    标签: java android uri android-contentprovider android-contacts


    【解决方案1】:

    您正在为您的联系人 URI 使用一个非常古老且已弃用的 Android API,称为“People”,永远不要使用 People 的 API,始终使用 ContactsContract。

    您应该像这样构建您的联系 uri:

    Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);

    除此之外,您的查询速度非常慢,您可以用一个快速查询替换这数百个查询,以使您的应用程序更快、更轻松,请参阅此答案中的示例代码: https://stackoverflow.com/a/47788324/819355

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多