如何在Android Studio中按删除特定联系人



所以我提出了这个问题,但没有人回答:如何在Android Studio中通过按下来识别联系人?

也许是因为它很难理解,所以我会简短地解释一下。

如何通过按压来移除特定联系人?

我看到了类似的问题,但我不知道在deleteContact(Context ctx, String phone, String name)参数中插入什么。

无论如何,这里使用的代码是:

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

我不知道这是否是在我的情况下使用的最佳代码,但这是连接到";删除联系人";MainActivity.java:中的按钮代码

Button rem_btn = findViewById(R.id.rem_btn);
rem_btn.setOnClickListener(v -> deleteContacts());

正如你所看到的,deleteContacts()需要参数,我只是不知道需要什么上下文(显然MainActivity中没有,但后来一半的代码消失了;我甚至不知道我的手机上附加了一个字符串;我也不知道这个名字是代表联系人的名字还是代表手机的名字(。

如果您想了解更多详细信息,链接位于顶部。

真的希望有人能帮助我。

嘿,我在我的应用程序中使用相同的代码,在所有设备中都可以完全正常工作,参数是

deleteContact(MainActivity.this, name eg-jhony, number eg-123578996) 

但是一定要在你的主要活动中添加这个来处理参数

public static boolean deleteContact(Context ctx, String name, String phone) {
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;
}

最新更新