如何从Android手机中获取已删除的联系人以及如何还原它

问题描述

我正在这样做,但这并没有为我获取电话号码。我正在使用接触提供者,我想从手机中获取已删除的联系人并将其还原到手机中。 预先感谢。

public static final String WHERE_MODIFIED1 = "( "+ ContactsContract.RawContacts.DELETED + "=1)";
public void readContacts() {
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query((ContactsContract.RawContacts.CONTENT_URI),null,WHERE_MODIFIED1,null);

    assert cur != null;
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String phone = null;
            //if (!(Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)) {
                System.out.println("name : " + name + ",ID : " + id);

                // get the phone number
                Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",new String[]{id},null);
                while (pCur.moveToNext()) {
                    phone = pCur.getString(
                            pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    System.out.println("phone" + phone);
                }
                pCur.close();
            //}
            if (phone != null) {
                contactList.add(new Contact(name,phone));
            }
            Log.e("hvy","onCreaterrView  Phone Number: name = " + name
                    + " No = " + phone);
        }
    }
    cur.close();
}

如果我运行此代码,我的日志将向我显示

E/hvy: onCreaterrView  Phone Number: name = Abc No = null
I/System.out: name : Abc,ID : 4090
E/hvy: onCreaterrView  Phone Number: name = Abc No = null
I/System.out: name : Abc,ID : 4091
E/hvy: onCreaterrView  Phone Number: name = Abc No = null
I/System.out: name : Gagaga,ID : 4092
E/hvy: onCreaterrView  Phone Number: name = Gagaga No = null
I/System.out: name : Shah,ID : 4093
E/hvy: onCreaterrView  Phone Number: name = Shah No = null
I/System.out: name : CardRecharge,ID : 4105

解决方法

只需将您要获取的ID传递到下面的代码

 ArrayList arrayList = new ArrayList();
    arrayList.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter("caller_is_syncadapter","true").build()).withSelection("_id=?",new String[]{String.valueOf(id)}).withValue("deleted",0).withYieldAllowed(true).build());
    try {
        YourActivity.this.getContentResolver().applyBatch("com.android.contacts",arrayList);
    } catch (OperationApplicationException e) {
        e.printStackTrace();
    } catch (RemoteException e) {
        e.printStackTrace();
    }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...