Question

I am new to android. So I request you to be patient with me. I am trying to write an application where on pressing a button the contacts API is opened. Then the user chooses the contact. Then I want to get the chosen contact in onAcitvityResult(int reqcode, int rescode, Intent data). Is there a way to do this without getting the Uri and querying for it through the whole database? This is my code where the second activity starts:

public void onClick(View v) {

      Log.d(TAG, "contact button clicked");
      Toast.makeText(ctx, "Contact button clicked",
      Toast.LENGTH_SHORT).show();

      Intent contacts = new Intent(Intent.ACTION_GET_CONTENT,Contacts.CONTENT_URI);
      contacts.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);

      startActivityForResult(contacts,1);
}

Am I correct in using Contacts.CONTENT_URI and Intent.ACTION_GET_CONTENT?

Is the intent I am using correct? I get the feeling that I should include email specifics here.

And this is where I deal with the result from activity:

protected void onActivityResult(int requestCode, int resultCode, Intent data){

    super.onActivityResult(requestCode, resultCode, data);
    String email=""; long id;
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {

            // get the contact ID
            Uri contacturi= data.getData();
            Cursor c= getContentResolver().query(contacturi,null,null,null,null);
            id = c.getLong(c.getColumnIndex(ContactsContract.Contacts._ID));
            c.close();

            // get the data package containing the email address for the contact
            c=getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                    new String[]{Email.DATA1}, 
                    ContactsContract.Data.CONTACT_ID + "=? AND " + Email.MIMETYPE + "=?",
                    new String[]{String.valueOf(id), Email.CONTENT_ITEM_TYPE}, null);

            email=c.getString(c.getColumnIndex(Email.DATA1));
            Log.d(TAG, "email is" + email);
        }
    }
    else {
        Log.d(TAG, "requestCode is not 1");
    }

    EditText ctext= (EditText) findViewById(R.id.contacttxt);
    ctext.append(email);
    Log.d(TAG, "onActivityResult() ends");
}

I am getting a runtime exception saying that failure delivering result.
Should I include some setResult() method??
Thank you in advance.

Was it helpful?

Solution

I got it :) You have to add c.moveToFirst(); two times, after the two initializations as the 2 cursors. But I am not getting why. Could anyone explain it?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top