Reputation: 271
I have a fragment where I'll do the following:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
Here I get for runOnUiThread
a warning may produce NullPointerException
.
The code works without problems.Android Studio suggests I change the code like this:
Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
@Override
public void run() {
is that sensible ? is there any other/better way ?
Upvotes: 6
Views: 2461
Reputation: 389
It depends on what your objective is :
1) You want the method caller to know he made a mistake by calling this method at a wrong state where getActivity()
private void myMethod() {
if(null == getActivity()) {
throw new IllegalStateException("Trying to call getActivity() at a state where the Activity equals null"); // Or new NullPointerException("")
}
// Do your stuff with getActivity()
}
2) You know that getActivity()
will not throw a NullPointerException
in your case :
private void myMethod() {
assert getActivity() != null;
// Do your stuff with getActivity()
}
3) You know that getActivity()
may be null, you don't want the app to suddenly stop :
private void myMethod() {
if(null == getActivity()) {
return;
}
// Do your stuff with getActivity()
}
Using Objects.requireNonNull() also requires api level 19 (4.4 (KITKAT))
You also have tons of information right here
Upvotes: 6
Reputation: 5228
(1) Use Flag isAdded
(fragment is added to host activity) before getActivity()
. This helps to avoid null pointer exception if the fragment is detached from the host activity.
if (isAdded() && null != getActivity()) {
// your logic
}
(2) requireNonNull(T obj)
Checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors.
Throws NullPointerException
- if obj is null
(application execution may terminate at this point).
Summary: As per your current context requireNonNull(T obj)
is not suitable. You must handle null
pointer gracefully.
Upvotes: 1
Reputation: 150
You could just add a null check, which may be more understandable.
if(getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
But also, you can use the method #requireActivity() This works as a getActivity but if the activity is null (if the fragment is detached) it will throw an IllegalStateException
https://developer.android.com/reference/android/support/v4/app/Fragment#requireActivity()
Upvotes: 2