android - 如何在android中使用上下文菜单删除联系人

标签 android

我尝试使用以下代码使用按名称选择的上下文菜单项删除联系人。

public static boolean deleteContact(Context ctx, String phone, String name) {

    Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
    Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
    try {
        if (cur.moveToFirst()) {
            do {
                if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
                    String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
                    ctx.getContentResolver().delete(uri, null, null);
                    return true;
                }

            } while (cur.moveToNext());
        }

    } catch (Exception e) {
        System.out.println(e.getStackTrace());
    }
    return false;
}

但我不知道如何将此代码放入我选择的上下文菜单项中

public boolean onContextItemSelected(MenuItem item)
{
    switch (item.getItemId()) 
    {
    case 0:

        return true;
    }
    return super.onContextItemSelected(item);
    }

最佳答案

这取决于您的代码。如果 onContextItemSelected 在您的 Activity 中:

ContactManager.deleteContact(MyActivity.this.getContext(), MyActivity.this.phone, MyActivity.this.name);

关于android - 如何在android中使用上下文菜单删除联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10512461/

相关文章:

android - 仅在应用程序未运行时从 Intent 启动 Activity

Android 在 NFC 标签上多次启动 Activity

Android Studio 1.4 gradle 在构建 baseGameUtils 时失败

java - 标识符预期困惑

android - 构建 Apk 错误 - 重复条目 : android/support/v4/database/DatabaseUtilsCompat. 类?

android - 有没有办法获得在android中调试的特定权限?

java - 构建android时出错

Android Studio 获取旧 Artifact

android - 有没有办法从下一次应用程序/进程崩溃测试继续进行 Espresso 测试?

android - 强制 droid sans 在应用程序中用作字体