Return result from fragment just as startActivityForResult in case Activity

138 Views Asked by At

I have an activity in which I am adding fragments.There is a Fragment(WhenFragment) on which I add another fragment (DateSelectionFragment) to get the date and when I back press I need that date and want to set in a text view.I used OnFragmentInteractionListener for this which returns result in WhenFragment correctly.But I am not able to access Textview in that OnFragmentInteractionListener implementation to set date to it.

@Override
public void onFragmentInteraction(Bundle bundle) {
   mBinding.textView.setText(bundle.getString("result"),"");
}

To get back to WhenFragment I am using

 getActivity().onBackPressed();
 mListener.onFragmentInteraction(bundle);

It is giving nullPointerException. Any help is highly appreciated.

2

There are 2 best solutions below

0
On

You can store the value in sharedPreferences and then fetch it later from elsewhere.

0
On

Try changing the back function as follows:-

 mListener.onFragmentInteraction(bundle);    
 getActivity().onBackPressed();

Or

if your are you are adding the second fragment using getChildFragmentManager() then , first the fragment stack has to be managed, instead of the activity stack .something like:-

 @Override
public void onBackPressed() {

// If the fragment exists and has some back-stack entry
if (mActivityDirectFragment != null && mActivityDirectFragment.getChildFragmentManager().getBackStackEntryCount() > 0){
    // Get the fragment fragment manager - and pop the backstack
    mActivityDirectFragment.getChildFragmentManager().popBackStack();
}
// Else, nothing in the direct fragment back stack
else{
    // Let super handle the back press
    super.onBackPressed();          
}
}

Some helpfull links:-

back stack behaviour with nested fragments

Sending data from nested fragments to parent fragment