简体   繁体   中英

how to Pick a Contact from phone book in android to spinner

Can anyone tell me how should i display the phone number and the contact name in a spinner? please help,Thanks in advance.

Use this code to load your contacts in an ArrayList and pass this to your Spinner's constructor

ArrayList<String> contacts = new ArrayList<String>();

        Cursor c = getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                null, null, null);
        while (c.moveToNext()) {

            String contactName = c
                    .getString(c
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phNumber = c
                    .getString(c
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            contacts.add(contactName + ":" + phNumber);

        }
        c.close();

Pass this to your Spinner like:

Spinner s = (Spinner) findViewById(R.id.Spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, contacts);
        s.setAdapter(adapter);

Don't forget to add the permission

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

in your manifest file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM