0
private void switchFragment(Fragment fragment) {
    if (getActivity() == null)
        return;

    ClassA pm = (ClassA) getActivity();
    pm.switchContent(fragment);
}

I am trying to switch fragments from ClassB, i am getting this exception when i try to do. I am trying to call the fragments of Class A Activity.

java.lang.ClassCastException: com.test.ClassB cannot be cast to com.test.ClassA

1 Answer 1

3

use instanceof for checking getActivity() type before casting it to ClassA or ClassB. try it as :

if (getActivity() instanceof ClassA) {
  ClassA pm = (ClassA) getActivity();
  pm.switchContent(fragment);
 } 
 else if (getActivity() instanceof ClassB) {
  ClassB pm = (ClassB) getActivity();
  pm.switchContent(fragment);
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Kevin : plz check this example for more help because currently you are trying to cast ClassB context to ClassA
I am using that example, but i am just thinking on if i am in ClassB context... then the fragments of Class A can never be called Being as Class A context... when we are in Class B

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.