Search code examples
androidandroid-fragmentsnotifydatasetchanged

notifyDataSetChanged() from different fragment


I currently have 3 fragments(tabs) and is currently using a viewpager. I have 1 listview for each fragment, and i want to notify the other when something happens, after clicking the view. I tried using the notifyDataSetChanged() on setOnPageChangeListener() on the mainactivity. Problem is, i can see the data being inserted when i change tabs. Since the change happens after changing tabs.


Solution

  • You may consider using broadcast receivers to notify data set change.

    In your receiving fragment

    public static final string RADIO_DATASET_CHANGED = "com.yourapp.app.RADIO_DATASET_CHANGED";
    
    private Radio radio;
    

    In the onCreate method :

    radio = new Radio();
    

    The radio class inside the receiving fragment :

    private class Radio extends BroadcastReceiver{
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent.getAction().equals(RADIO_DATASET_CHANGED)){
                        //Notify dataset changed here
                    }
            }
    

    In the receiving fragment on resume method :

    @Override
            protected void onResume() {
                super.onResume();                    
                    //using intent filter just in case you would like to listen for more transmissions
                    IntentFilter filter = new IntentFilter();
                    filter.addAction(RADIO_DATASET_CHANGED);                    
                    getActivity().getApplicationContext().registerReceiver(radio, filter);
            }
    

    Make sure we unregister receiver in the onDestroy method

     @Override
    protected void onDestroy() {
        super.onDestroy();
    
        try {
            getActivity().getApplicationContext().unregisterReceiver(radio);
        }catch (Exception e){
            //Cannot unregister receiver
        }
    
    }
    

    Fragment transmitting dataset changed

    Then from the fragment which is notifying datasetchange just do :

    Intent intent = new Intent(ReceivingFragment.RADIO_DATASET_CHANGED);
    getActivity().getApplicationContext().sendBroadcast(intent);