user2135367
user2135367

Reputation:

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.

Upvotes: 1

Views: 2844

Answers (2)

J.Vassallo
J.Vassallo

Reputation: 2292

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);

Upvotes: 3

Arun Ravichandran
Arun Ravichandran

Reputation: 208

In your MainActivity .Try with this code. It may help.

 @Override
    public void onPageSelected(int position) {
        // TODO Auto-generated method stub
        if (position ==0 )
            viewPager.getAdapter().notifyDataSetChanged();
        if (position == 1)
            viewPager.getAdapter().notifyDataSetChanged();
if (position == 2)
            viewPager.getAdapter().notifyDataSetChanged();
    }

Upvotes: 0

Related Questions