get parent activity by a fragment

1.2k Views Asked by At

I'm currently having two activities, MainActivity and ResultActivity and both of them will use the same fragment - Favorite. my question is: How to know which activity is containing the fragment? For example I have a fragment A inside activity ResultActivity, and how can I know if fragment A is contained in ResultActivity or MainActivity?

2

There are 2 best solutions below

1
On

You can check an instance of this activity.

getActivity() - can return null value, so you need check this.

Java

        if (getActivity() != null && getActivity() instanceof MainActivity) {
//          TODO
        } else if (getActivity() !=null && getActivity() instanceof ResultActivity) {
//            TODO
        }

Kotlin

        if (activity !=null && activity is MainActivity) {
//          TODO
        } else if (activity !=null && activity is ResultActivity) {
//            TODO
        }

Edited: you can also use another method requireActivity the difference is that you receive notNull value, but if activity null you can get IllegalStateException.

requireActivity() - return notNull value but can throw Exception.

      try {
        if (requireActivity() instanceof MainActivity) {
            //          TODO
        } else if (requireActivity) instanceof ResultActivity) {
            //            TODO
        }
    }catch (Exception e){}

Kotlin

        try {
        if (requireActivity() is MainActivity) {
            //          TODO
        } else if (requireActivity) is ResultActivity) {
            //            TODO
        }
    }catch (Exception e){}
3
On

I think this is the best practice for you.

And to get Activity you should use requireActivity()

And to get Context you should use requireContext()

// for kotlin
fun isMainActivity(): Boolean {
    return requireActivity() is MainActivity
}

public boolean isMainActivity() {
    return requireActivity() instanceof MainActivity;
}