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 ?
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With