如何从联系人列表中获取手机号码



嗨,我想获取手机号码并将其设置为edittext字段中。

Button onclick()

btnContacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, PICK_CONTACT);
            }
        });

onActivityResult()代码:

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        Cursor cursor = null;
       // mName.setText(context.getString(R.string.not_available));
       // mNumber.setText(context.getString(R.string.not_available));
        if(requestCode == PICK_CONTACT && resultCode == RESULT_OK && data != null){
           // Log.d(TAG, "requestCode, resultCode, data ok");
            Uri uri = data.getData();
            try{
                String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER};
//              cursor =  getContentResolver().query(uri, projection, null, null, null);
                cursor =  getContentResolver().query(uri, null, null, null, null);
                cursor.moveToFirst();
               // Log.d(TAG, "Trying to retrieve the name and the number");
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String hasNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER));
                //Log.d(TAG, "hasNumber "+hasNumber);
                //mName.setText(name);

                 //   Log.d(TAG, "contact has telephone number");
                    //set name and number
                    String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                  //  mNumber.setText(phoneNumber);
                    Toast toast = Toast.makeText(getApplicationContext(),phoneNumber, Toast.LENGTH_SHORT);
                    toast.show();

            }catch(Exception ex){
                Toast toast = Toast.makeText(getApplicationContext(),"fail", Toast.LENGTH_SHORT);
                toast.show();
            }
            if(cursor!= null && !cursor.isClosed()){
                cursor.close();
            }
        }else{
            Toast toast = Toast.makeText(getApplicationContext(),"failed", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

当我单击button时,通讯录会打开,当我选择一个联系人时,会抛出一些错误

日志:

Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 36 columns.

我哪里做错了?

ContactsContract有很多列。列ContactsContract.CommonDataKinds.Phone.NUMBER可能不包含手机号码。它可能不包含任何内容...

您需要滚动浏览输入的所有电话号码,如下所示:

如何在安卓中获取联系人的电话号码

您可以修改代码以尝试仅获取类型为 MOBILE 的列 - 但请记住,用户很懒惰,不太可能正确标记电话号码。如果存在多个号码,您可能应该提示用户选择手机号码。

最新更新