Difference between getContext() and requireContext() when using fragments

getContext() returns a nullable Context.

requireContext() returns a nonnull Context, or throws an exception when one isn't available.

If your code is in a lifecycle phase where you know your fragment is attached to a context, just use requireContext() to get a Context and also keep static analyzers happy about potential NPE issues.

If your code is outside of regular fragment lifecycle (say, an async callback), you might be better off using getContext(), checking its return value yourself and only proceeding using it if it was non-null.

Being explicit with nullability is even more important in Kotlin where it is built into the language's type system.


While Laalto's answer is correct, I'm adding the code to prove the difference between requireContext() and getContext.

In Fragment.java you should see the following code.

@NonNull
    public final Context requireContext() {
        Context context = getContext();
        if (context == null) {
            throw new IllegalStateException("Fragment " + this + " not attached to a context.");
        }
        return context;
    }

You can see that the requireContext() method throws an exception when the context is null.

@Nullable
    public Context getContext() {
        return mHost == null ? null : mHost.getContext();
    }

On the other hand, If you see the code for getContext(), there is a chance that you might get a null value when called.