0

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?

xxddd_69
  • 83
  • 1
  • 7

2 Answers2

1

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){}
Yura
  • 363
  • 3
  • 10
0

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;
}
  • Thanks for your answer, may I ask the difference between requireActivity() and getActivity()? I can’t find a proper answer for it – xxddd_69 Dec 05 '21 at 11:52
  • https://stackoverflow.com/a/61045701/5429327 – Yura Dec 05 '21 at 15:51
  • this answer is also correct, the only difference is where the error will be inside method requireActivity or your implementation when you try to check Null value) But I have updated the answer. – Yura Dec 05 '21 at 16:15