0

I am trying to refresh a currently selected fragment inside of a ViewPager. I am using one MainActivity as a way to communicate between multiple fragments via interface calls. The fragment I am working with is implementing an interface call to the ViewPagerAdapter, however, when attaching the listener to the fragment I receive a ClassCastException error "Activity cannot be cast to Fragment". This is the code below:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mListener = (UpdateableFragment) context; **//ERROR HERE**
}

I am trying to follow the answer posted here https://stackoverflow.com/a/17855730, however i cannot figure out where the interface call should be handled. Currently i have it implemented in the ViewPagerAdapter, so when i need to update i can just notifyDataSetChange(), but it returns the ClassCastException error.

I have tried to handle the interface call in the MainActivity i am using to communicate with the rest of my fragments and this eliminates the ClassCastException error, however, i have no way to call the ViewPagerAdapter and notifyDatasetChange. Below is my code:

CurrentFragment (in ViewPager)

private UpdateableFragment mListener;

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mListener = (UpdateableFragment) context; **//ERROR HERE**
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public void click(){
    mListener.update();
}
public interface UpdateableFragment {
    void update();
}

ViewPagerAdapter

public class ViewPagerAdapter extends FragmentPagerAdapter implements CurrentFragment.UpdateableFragment{

public ViewPagerAdapter(FragmentManager fm) {
    super(fm);}


//Note: unnecessary code left out.

public void update() {
    notifyDataSetChanged();
}

@Override
public int getItemPosition(Object object) {
    if (object instanceof CurrentFragment.UpdateableFragment) {
        ((CurrentFragment.UpdateableFragment) object).update();
    }
    return super.getItemPosition(object);
}

Any feedback would be appreciated. Thanks.

2 Answers2

0

In onAttach(Context context) , the context is means of Activity, so cast context to your interface will throw the cast exception, if you want to communication with each fragments, i think you can try Event Bus library.

yu wang
  • 283
  • 1
  • 6
0

Try to use onAttachFragment() instead of onAttach():

@Override
public void onAttachFragment(Fragment childFragment) {
    confirmListener = (ConfirmListener) childFragment;
}
Sam Chen
  • 7,597
  • 2
  • 40
  • 73