Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

requireActivity() and requireContext() in kotlin

What is the purpose of requireActivity() and requireContext() in Fragment?

like image 352
jitendra namde Avatar asked Nov 04 '19 12:11

jitendra namde


2 Answers

Because they might be null. In java you can just call for them. But in Kotlin they are declared as nullable return types. So you have 3 options:

  1. You are not sure if it is null or not: activity?.let { //do what you need to do.}
  2. You are sure it will not be null so you can call activity!!.doSomething but it is ugly.
  3. This is the cleanest option where you are sure it will not be null, but if somehow it is, there will be a specific exception(IllegalStateException) prepared for this and it will be thrown and not generic NullPointerException.
like image 83
Yavor Mitev Avatar answered Nov 12 '22 05:11

Yavor Mitev


Check the official Android Source code documentation. Those methods return activity/context with a null check.

requireActivity()

public final FragmentActivity requireActivity() {
        FragmentActivity activity = getActivity();
        if (activity == null) {
            throw new IllegalStateException("Fragment " + this + " not attached to an activity.");
        }
        return activity;
    }

requireContext()

public final Context requireContext() {
        Context context = getContext();
        if (context == null) {
            throw new IllegalStateException("Fragment " + this + " not attached to a context.");
        }
        return context;
    }
like image 23
Prokash Sarkar Avatar answered Nov 12 '22 07:11

Prokash Sarkar