Android从联系人列表中获取电话号码

时间:2022-04-06 22:55:24

I have these codes which basically use a ListView to display the names in the contact list and I want to get their phone number when click each single name:

我有这些代码,基本上使用ListView来显示联系人列表中的名字,我想在点击每个名字时获得他们的电话号码:

final ContentResolver cr = getContentResolver();

final Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
myCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {ContactsContract.Contacts.DISPLAY_NAME}, new int[]{R.id.TVRow}, 0);
myPhoneList.setAdapter(myCursorAdapter);

myPhoneList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        c.moveToPosition(position);
        Toast.makeText(getApplicationContext(), c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)), Toast.LENGTH_SHORT).show();
    }
});

In the onItemClick Method the

在onItemClick方法中。

    GetColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)

returns -1 and therefore I cannot get the phone number with this method.

返回-1,因此我无法使用此方法获得电话号码。

I've also tried to print out all the columns of the cursor c and it returns 34 columns but the only column which seems to be related to the phone number is HasPhoneNumber.

我还尝试打印出游标c的所有列,它返回34列,但似乎唯一与电话号码相关的列是HasPhoneNumber。

So where's the problem and how can I fix it? Thanks!

那么问题在哪里,我该如何解决呢?谢谢!


The updated version, where the String array passed to construct myCursorAdapter is changed:

更新后的版本,其中传递给构造myCursorAdapter的字符串数组被更改:

final ContentResolver cr = getContentResolver();

    final Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    myCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER}, new int[]{R.id.TVRow}, 0);
    myPhoneList.setAdapter(myCursorAdapter);

    myPhoneList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){
            c.moveToPosition(position);
            Toast.makeText(getApplicationContext(), c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)), Toast.LENGTH_SHORT).show();
        }
    });

I suppose the updated code will show the phone numbers in the ListView but I got an error says "column 'data1' does not exist".

我想更新后的代码将显示ListView中的电话号码,但我得到一个错误消息,说“列'data1'不存在”。

3 个解决方案

#1


0  

The ContactsContract Android API stores data about contacts like phone number in the Data table, not the Contacts table.

ContactsContract Android API在数据表(而不是联系人表)中存储联系人的数据,比如电话号码。

Read this carefully: https://developer.android.com/reference/android/provider/ContactsContract.html.

仔细阅读这个:https://developer.android.com/reference/android/provider/ContactsContract.html。

Update - here's a fixed version of your code (untested):

更新-这是你的代码的一个固定版本(未经测试):

final ContentResolver cr = getContentResolver();
String[] projection = new String[] {Contacts.DISPLAY_NAME, Phone.NUMBER};
final Cursor c = cr.query(Data.CONTENT_URI, projection, null, null, null);
myCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {Phone.NUMBER}, new int[]{R.id.TVRow}, 0);
myPhoneList.setAdapter(myCursorAdapter);

myPhoneList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        c.moveToPosition(position);
        Toast.makeText(getApplicationContext(), c.getString(1), Toast.LENGTH_SHORT).show();
    }
});

#2


1  

First of all add this line in AndroidManifest.xml to take permission from user.

首先,在AndroidManifest中添加这一行。获取用户权限的xml。

<uses-permission android:name="android.permission.READ_CONTACTS"/>

implement the button of contact

实现联系人按钮

        phoneContactsButtton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
            // The below two line is needed to open the contact list of  mobile
                Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(contactPickerIntent,1);

            }
        });

you have to override the onActivityResult() which will be written to the outside of onCreate() mehtod similar to this

您必须重写onActivityResult(),它将被写入onCreate() mehtod的外部,与此类似

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


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode){
        case 1 :
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();

                Cursor cur =  getContentResolver().query(contactData, null, null, null, null);
                if (cur.getCount() > 0) {// thats mean some resutl has been found
                    if(cur.moveToNext()) {
                        String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                        String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        Log.e("Names", name);

                        if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                        {

                            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
                            while (phones.moveToNext()) {
                                String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                Log.e("Number", phoneNumber);
                            }
                            phones.close();
                        }

                    }
                }
                cur.close();
            }
            break;
    }

}

#3


0  

it returns -1 because you don't request the column ContactsContract.CommonDataKinds.Phone.NUMBER from DB:

它返回-1,因为您不请求列ContactsContract.CommonDataKinds.Phone。从DB数量:

new String[] {ContactsContract.Contacts.DISPLAY_NAME}

ContactsContract.Contacts.DISPLAY_NAME is the only field you request.

ContactsContract.Contacts。DISPLAY_NAME是您请求的惟一字段。

To be able to get the phone number, you firstly need to include it into list of columns you want to get from DB:

要想获得电话号码,你首先需要将它包含到你想从DB中获取的列列表中:

new String[] {ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}

新String[]{ ContactsContract.Contacts。DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER }

Now you have to override adapter's getView so it sets the name into the textView of the list row. After that your onItemClick will work as expected

现在您必须重写适配器的getView,以便它将名称设置为列表行的textView。之后,onItemClick将按预期工作

#1


0  

The ContactsContract Android API stores data about contacts like phone number in the Data table, not the Contacts table.

ContactsContract Android API在数据表(而不是联系人表)中存储联系人的数据,比如电话号码。

Read this carefully: https://developer.android.com/reference/android/provider/ContactsContract.html.

仔细阅读这个:https://developer.android.com/reference/android/provider/ContactsContract.html。

Update - here's a fixed version of your code (untested):

更新-这是你的代码的一个固定版本(未经测试):

final ContentResolver cr = getContentResolver();
String[] projection = new String[] {Contacts.DISPLAY_NAME, Phone.NUMBER};
final Cursor c = cr.query(Data.CONTENT_URI, projection, null, null, null);
myCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {Phone.NUMBER}, new int[]{R.id.TVRow}, 0);
myPhoneList.setAdapter(myCursorAdapter);

myPhoneList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        c.moveToPosition(position);
        Toast.makeText(getApplicationContext(), c.getString(1), Toast.LENGTH_SHORT).show();
    }
});

#2


1  

First of all add this line in AndroidManifest.xml to take permission from user.

首先,在AndroidManifest中添加这一行。获取用户权限的xml。

<uses-permission android:name="android.permission.READ_CONTACTS"/>

implement the button of contact

实现联系人按钮

        phoneContactsButtton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
            // The below two line is needed to open the contact list of  mobile
                Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(contactPickerIntent,1);

            }
        });

you have to override the onActivityResult() which will be written to the outside of onCreate() mehtod similar to this

您必须重写onActivityResult(),它将被写入onCreate() mehtod的外部,与此类似

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


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode){
        case 1 :
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();

                Cursor cur =  getContentResolver().query(contactData, null, null, null, null);
                if (cur.getCount() > 0) {// thats mean some resutl has been found
                    if(cur.moveToNext()) {
                        String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                        String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        Log.e("Names", name);

                        if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                        {

                            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
                            while (phones.moveToNext()) {
                                String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                Log.e("Number", phoneNumber);
                            }
                            phones.close();
                        }

                    }
                }
                cur.close();
            }
            break;
    }

}

#3


0  

it returns -1 because you don't request the column ContactsContract.CommonDataKinds.Phone.NUMBER from DB:

它返回-1,因为您不请求列ContactsContract.CommonDataKinds.Phone。从DB数量:

new String[] {ContactsContract.Contacts.DISPLAY_NAME}

ContactsContract.Contacts.DISPLAY_NAME is the only field you request.

ContactsContract.Contacts。DISPLAY_NAME是您请求的惟一字段。

To be able to get the phone number, you firstly need to include it into list of columns you want to get from DB:

要想获得电话号码,你首先需要将它包含到你想从DB中获取的列列表中:

new String[] {ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}

新String[]{ ContactsContract.Contacts。DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER }

Now you have to override adapter's getView so it sets the name into the textView of the list row. After that your onItemClick will work as expected

现在您必须重写适配器的getView,以便它将名称设置为列表行的textView。之后,onItemClick将按预期工作