In many cases, we have to use the operations of selecting contacts. It is very troublesome to write it by ourselves. Instead, it is better to directly call the system's address book.
Let's look at the requirements below:
Requirements:
When an edittext button is clicked, go to the system address book. Select one address book item and return it to the current interface.
The username of the selected contact number is displayed on edittext.
Go directlyCode:
Import Android. App. activity; Import Android. content. contentresolver; Import Android. content. intent; Import Android. database. cursor; Import Android.net. Uri; Import Android. OS. Bundle; Import Android. provider. contactscontract; Import Android. View. view; Import Android. widget. edittext; Public Class Mainactivity Extends Activity {edittext text; string username, usernumber; @ override Public Void Oncreate (bundle savedinstancestate ){ Super . Oncreate (savedinstancestate); setcontentview (R. layout. activity_main); text = (Edittext) findviewbyid (R. Id. Number );} Public Void Click (view v) {startactivityforresult ( New Intent (intent. action_pick, contactscontract. Contacts. content_uri ), 0 ) ;}@ Override Protected Void Onactivityresult ( Int Requestcode, Int Resultcode, intent data ){ Super . Onactivityresult (requestcode, resultcode, data ); If (Resultcode = Activity. result_ OK) {contentresolver recontentresolverol =Getcontentresolver (); Uri contactdata = Data. getdata (); @ suppresswarnings ( "Deprecation" ) Cursor = Managedquery (contactdata, Null , Null , Null , Null ); Cursor. movetofirst (); Username = Cursor. getstring (cursor. getcolumnindex (contactscontract. Contacts. display_name); string contactid =Cursor. getstring (cursor. getcolumnindex (contactscontract. Contacts. _ id); cursor phone = Recontentresolverol. Query (contactscontract. commondatakinds. Phone. content_uri, Null , Contactscontract. commondatakinds. Phone. contact_id + "=" + Contactid, Null , Null ); While (Phone. movetonext () {usernumber = Phone. getstring (phone. getcolumnindex (contactscontract. commondatakinds. Phone. Number); text. settext (usernumber + "(" + Username + ")" );}}}}
You need to add permissions:
<Uses-Permission Android: Name = "android. Permission. read_contacts"/>
<Uses-Permission Android: Name = "android. Permission. write_contacts"/>