通过Uri获取手机通讯录的某个联系人

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null && cursor.getCount()>0 &&cursor.moveToFirst()) {
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone!=null && phone.getCount()>0) {
                while(phone.moveToNext()){
                    contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
            }else{
                phone.close();
                cursor.close();
                return null;       ----  ①
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    当选择某个联系人,但是没有给它设置手机号码时,代码会在①的地方返回null,所以勿忘调用getPhoneContacts之后判断是否为null。否则会报异常:

java.lang.NullPointerException: Attempt to read from null array。

你可能感兴趣的:(API)