androidandroid-fragmentslocalbroadcastmanager

Fragment to Fragment communication fails using LocalBroadcastManager


I am having a problem transfering data from one fragment to another using LocalbroadcastManager.

FragmentA has editText and onclick on it will launch FragmentB. FragmentB has a list of items and onclick on each item I want to pass the data to FragmentA.

Here is my implementation.

public class FragmentA extends Fragment {
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String highSchoolName = intent.getStringExtra("HighSchoolName");
    }
};

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LocalBroadcastManager.getInstance(getContext()).registerReceiver(mMessageReceiver, new IntentFilter("HighSchoolEvent"));
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mMessageReceiver);
}

Below is Fragment B where broadcast message is sent from.

public class FragmentB extends Fragment {

    mHighSchoolListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            HighSchool highSchoolItem = mHighSchoolAdapter.getItem(position);
            sendHighSchoolItemToSignupForm(highSchoolItem);
        }
    });

    private void sendHighSchoolItemToSignupForm(HighSchool highSchoolItem) {
        Intent intent = new Intent("HighSchoolEvent");
        intent.putExtra("HighSchoolName", highSchoolItem.getName());
        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
        getActivity().onBackPressed();
    }
}

Debug / Logging never hits the onReceive message of Broadcast receiver. Is there anything missing? Appreciate any suggestions.


Solution

  • If "launch" means you are replacing Fragment A with Fragment B, then you are going wrong..

    You should add Fragment B to backstack

    FragmentTransaction#addToBackStack(String fragmentName);
    

    and you should do

    FragmentTransaction#add()

    instead of

    FragmentTransaction#replace()

    Add: will add another Fragment View to container

    Replace: will replace all the contents of a container with another Fragment

    I am sure you are replacing Fragment A with Fragment B and in that case your Fragment A will get destroyed and Fragment B will be loaded, you wont be able to listen to updates anymore in Fragment A