问题
I'm following the answer https://stackoverflow.com/a/867828/129805 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;
}
}
回答1:
The singleInstance fires the callback immediately. You have more info in this link
来源:https://stackoverflow.com/questions/32644502/why-is-onactivityresult-is-called-before-a-contact-is-chosen