Tuesday, November 18, 2014

Open Contacts using Intent and get Contact in onActivityResult()

Here, I am launching contacts from my app using a button click. I am opening contacts which have phone numbers. Here we are launching contacts using startActivityForResult, so while returning back to the app, app will get the selected contact info in onActivityResult() of Activity class.

The code snippet is as,

 ((Button) findViewById(R.id.btn_openContacts)).setOnClickListener(new View.OnClickListener() {  
                public void onClick(View v) {  
                     Intent i = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);  
                     startActivityForResult(i, PICK_CONTACT);  
onActivityResult() will be look like this,
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
           super.onActivityResult(requestCode, resultCode, data);  
           Log.i(TAG, "onActivityResult()");  
           if (requestCode == PICK_CONTACT) {  
                if (resultCode == Activity.RESULT_OK) {  
                     Uri contactsData = data.getData();  
                     CursorLoader loader = new CursorLoader(this, contactsData, null, null, null, null);  
                     Cursor c = loader.loadInBackground();  
                     if (c.moveToFirst()) {  
                          Log.i(TAG, "Contacts ID: " + c.getString(c.getColumnIndex(Contacts._ID)));  
                          Log.i(TAG, "Contacts Name: " + c.getString(c.getColumnIndex(Contacts.DISPLAY_NAME)));  
                          Log.i(TAG, "Contacts Phone Number: " + c.getString(c.getColumnIndex(Phone.NUMBER)));  
                          Log.i(TAG, "Contacts Photo Uri: " + c.getString(c.getColumnIndex(Photo.PHOTO_URI)));  

Here I am just getting the details and getting in the Logcat. Just to verify I am getting the contact details

The screenshots are,