Why is onActivityResult is called before a contact is chosen?
Asked Answered
T

1

1

I'm following the answer https://mcmap.net/q/167632/-how-to-call-android-contacts-list to add a contact picker to my app.

The problem is that onActivityResult is immediately invoked with the correct reqCode (PICK_CONTACT), but with aresultCode of 0 and a null for data.

It is not invoked again, when the user actually picks a contact.

The AndroidManifest gives this activity android:launchMode="singleInstance"> as I only ever want there to be one instance.

What have I done wrong?

MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    addContactButton = (Button) findViewById(R.id.addContactButton);
    addContactButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(intent, PICK_CONTACT);
        }
    });
}

@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    Log.d(TAG, "onActivityResult");
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
        case (PICK_CONTACT) :
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
                Cursor c =  getContentResolver().query(contactData, null, null, null, null);
                if (c.moveToFirst()) {
                    String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    // TODO Whatever you want to do with the selected contact name.
                    Log.d(TAG, "you chose " + name + ".");
                }
            }
            break;
    }
}
Trela answered 18/9, 2015 at 5:31 Comment(6)
Is this happening on a particular device or is it happening everywhere?Elonore
There seems to be nothing wrong with your code, have you tried removing android:launchMode="singleInstance" just for testing ?Unto
@SharpEdge - I'll try that tomorrow, but I do need singleInstance.Trela
@Elonore Sorry, I only have one phone.Trela
Try it on an emulator.Elonore
@chrisdew I've used this code in all my apps using startActivityForResult and its straight forward.. however the only addition you have is the "singleInstance" so it was just a lucky guess.Unto
B
1

The singleInstance fires the callback immediately. You have more info in this link

Beitnes answered 18/9, 2015 at 7:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.