suchen

Heim  >  Fragen und Antworten  >  Hauptteil

android跳转联系人并返回数据无法获得点击项的电话

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.buttonQuary);
    name = (TextView) findViewById(R.id.tv_name);
    phone = (TextView) findViewById(R.id.tv);
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Uri uri = Uri.parse("content://contacts/people");
            Intent intent = new Intent(Intent.ACTION_PICK, uri);
            startActivityForResult(intent, 0);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case 0:
            if (data == null) {
                return;
            }
            //处理返回的data,获取选择的联系人信息
            Uri uri = data.getData();
            getPhoneContacts(uri);
            name.setText(myname);
            phone.setText(phonenumber);
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

private String[] getPhoneContacts(Uri uri) {
    String[] contact = new String[2];
    //得到ContentResolver对象
    ContentResolver cr = getContentResolver();
    //取得电话本中开始一项的光标
    Cursor cursor = cr.query(uri, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        //取得联系人姓名
        int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        myname = 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.moveToFirst();
            phonenumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        }
        phone.close();*/
        cursor.close();
    } else {
        return null;
    }
    return contact;
}

以上是代码, 这样是可以运行的,能获取到名字,我注释掉的部分是获取电话的,无法获取到所以注释掉,求解决啊

天蓬老师天蓬老师2772 Tage vor466

Antworte allen(1)Ich werde antworten

  • 大家讲道理

    大家讲道理2017-04-17 17:45:21

    代码是没有问题,不过这段代码需要添加权限<uses-permission android:name="android.permission.READ_CONTACTS" />
    不知你的问题是返回null还是直接报权限问题错误;

    Antwort
    0
  • StornierenAntwort