Lena Bru
Lena Bru

Reputation: 13947

startActivityForResult from dialog fragment

Somewhere in my app i have a Dialog fragment, that starts an activityForResult

The problem - onActivityResult does no get called when i exit the called activity

The stranger problem - i put debug points on the onActivityResult method, it is called!!! just not when the activity ends, but BEFORE the activity is displayed fully on the screen

This is my code:

this is written in the dialog fragment

btnSelectContacts.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent contactPicker = new Intent(getActivity(), ContactPickerActivity.class);
            contactPicker.putExtra(ContactData.CHECK_ALL, false);
            startActivityForResult(contactPicker, REQ_SELECT_CONTACTS);
        }
    });

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (data != null && data.hasExtra(ContactData.CONTACTS_DATA)) {
              data.setAction(IntentKeys.CONTACTS);
              getActivity().sendBroadcast(data);
             }

            }

What i am seeing is unexpected life cycle behaviour the call stack goes like this

ImageButton click ImageButton onClickListener called startActivityForResult onActivityResult of the activity it is in, of the dialog fragment it is in, of the fragment itself is called onResume of the called activity is called called activity does

Intent result = new Intent();         

    ArrayList<ContactData> resultList = contactsAdapter.items;
    Iterator<ContactData> iterResultList = resultList.iterator();

    ArrayList<ContactData> results = new ArrayList<ContactData>();
    //pass only checked contacts
    while(iterResultList.hasNext()) {

        ContactData contactData = iterResultList.next();
        if(contactData.checked) {
            results.add(contactData);
        }
    }

    result.putParcelableArrayListExtra(ContactData.CONTACTS_DATA, results);

    setResult(Activity.RESULT_OK, result);
    finish();

and then just onResume of the dialog fragment is called instead of the expected onActivityResult

what am i doing wrong?!

Upvotes: 4

Views: 5292

Answers (1)

Murtaza Khursheed Hussain
Murtaza Khursheed Hussain

Reputation: 15336

to start activity from fragment :

getActivity().startActivityForResult(intent, code);

to get result back in fragment :

in your parent activity (fragment call activity) :

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

    fragmentObject
            .onActivityResult(requestCode, resultCode, data);
}

Upvotes: 10

Related Questions