Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?!

like image 288
Lena Bru Avatar asked Dec 25 '22 01:12

Lena Bru


1 Answers

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);
}
like image 108
Murtaza Khursheed Hussain Avatar answered Jan 09 '23 21:01

Murtaza Khursheed Hussain