Select a contact from the from address book using People Provider and URI

2 votes · 1 comment

Select a contact from your address book on the phone. Note that you have to first have contacts in your phone book from which to select an entry. You can download the full source for this here: http://github.com/novoda/android/tree/master/ContactSelector/

raw ·
copy
· download
/*** * src/com.novoda/ContactSelector.Java * public class ContactSelector extends Activity { public static final int PICK_CONTACT = 1; private Button btnContacts; private TextView txtContacts; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnContacts = (Button) findViewById(R.id.btn_contacts); txtContacts = (TextView) findViewById(R.id.txt_contacts); btnContacts.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT); } }); } @Override public void onActivityResult(int reqCode, int resultCode, Intent data) { super.onActivityResult(reqCode, resultCode, data); switch (reqCode) { case (PICK_CONTACT): if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); Cursor c = managedQuery(contactData, null, null, null, null); if (c.moveToFirst()) { String name = c.getString(c.getColumnIndexOrThrow(People.NAME)); txtContacts.setText(name); } } break; } } } /*** * res/layout/main.xml * <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/btn_contacts" android:layout_marginLeft="8px" android:layout_width="60px" android:layout_height="60px" /> <TextView android:id="@+id/txt_contacts" android:textSize="24sp" android:layout_margin="8px" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> /*** * AndroidManifest.xml * <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.novoda" android:versionCode="1" android:versionName="1.0"> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-sdk android:minSdkVersion="3" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".ContactSelector" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Add a comment

1 Comment

hello.., i use this code .. but my phone goes to hang up and it force close .. how to solve this?.. thanks in advance...

Reply · Feb. 17, 2014, 6:22 a.m.