Search code examples
androidbroadcastreceiver

Android How to pass data from Activity to Fragment once successful volley request?


I want to pass data from an activity to a fragment via BroadcastReceiver. But I cant get the data in the fragment,cause the onReceive() there not fire up.

In my AppConfig:

public static final String CREATE_POST = "created_post";

In activity A implement all this stuff :

 StringRequest request = new StringRequest(Request.Method.POST, AppConfig.MYURL, new Response.Listener<String>(){
            @Override
            public void onResponse(String response) {

    Intent intent = new Intent(AppConfig.CREATE_POST);
    intent.putExtra("myId",myId);
    intent.putExtra("userId",userId);
    intent.putExtra("username",username);

    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

In the fragment with should be receive the data I already implement this :

private BroadcastReceiver broadcasterReceiver;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

//..other code here

    broadcasterReceiver = new BroadcastReceiver() {
       @Override
       public void onReceive(Context context, Intent intent) {
          if(intent.getAction().equals(AppConfig.CREATE_POST)){
             Log.d("Broadcast","get called")
             //HERE I get the intent here
          }
       }

 }


//I already register the boardcast in onResume() and onPause()
@Override
    public void onResume() {
        super.onResume();
        //register the broadcaster
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcasterReceiver,
                new IntentFilter(AppConfig.CREATE_POST));
    }

  @Override
  public void onPause() {
    super.onPause();
   //unregister the broadcaster
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcasterReceiver);
    }

What I still missing out? In order to make this work.


Solution

  • First of all, create an interface anywhere in your package. For eg -

    public interface SyncDataListener {
        void refreshDashboard(String myId, String username, String userId);
    }
    

    Then in your Activity, create a global declaration and setter/resetter methods like -

    private SyncDataListener syncDataListener;
    
    public void setSyncDataListener(SyncDataListener syncDataListener) {
        this.syncDataListener = syncDataListener;
    }
    
    public void resetSyncDataListener(){
        syncDataListener = null;
    }
    

    Next in your Fragment implement the above interface and override the method like -

    public class DashboardFragment extends Fragment implements SyncDataListener {  
        @Override
        public void refreshDashboard(String myId, String username, String userId) {
            //Your code that deals with the data received from activity
        }
    }
    

    Also in the Fragment's onAttach(Context context) method call the setter method created in the activity like -

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        ((MainActivity) getActivity()).setSyncDataListener(this);
    }
    

    Also make sure you reset the listener instance when your Fragment gets destroyed like -

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ((MainActivity) getActivity()).resetSyncDataListener();
    }
    

    Now whenever you need to send data from Activity to Fragment you can call -

    if (syncDataListener != null) {
        syncDataListener.refreshDashboard(myId, username, userId);
    }