Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've been having this doubt since a long time, when I'm working with android fragments and I need to instantiate a Context, or I need to pass a Context as argument for other function, I can choose to use between getContext() and requireContext() methods to achieve that, I normally prefer to use requireContext(), but just because the IDE(Android Studio) shows warnings sometimes when I use the getContext().But the result of using one or other method seems to be the same, no matter what I choose.

My question is, is there any difference between these two methods? If this is the case, which one is better, or which should I use in each case?

like image 566
Ariel Avatar asked Feb 25 '20 20:02

Ariel


People also ask

What is requireContext in fragment?

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.

What is the difference between getContext and getActivity?

getContext() - Returns the context view only current running activity. getActivity()- Return the Activity this fragment is currently associated with. getActivity() can be used in a Fragment for getting the parent Activity of the Fragment .

Should we use requireContext?

TLDR: use requireContext only when you are sure fragment is attached to its host(onResume, onViewCreated, etc). Android team annotated some sdk methods with NonNull and Nullable in support library in 27.1. 0. That change leads to warnings and errors like on the picture above.

What is difference between context and activity?

Both the Activity and Application classes extend the Context class. In android, Context is the main important concept and the wrong usage of it leads to memory leakage. Activity refers to an individual screen and Application refers to the whole app and both extend the Context class.


2 Answers

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.

like image 67
laalto Avatar answered Sep 30 '22 15:09

laalto


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.

like image 32
Nagaraj Alagusundaram Avatar answered Sep 30 '22 16:09

Nagaraj Alagusundaram