6

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 ?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
DavDeveloper
  • 261
  • 1
  • 17

3 Answers3

6

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

Hocine B
  • 391
  • 2
  • 8
2

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()

1

(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.

Mable John
  • 4,518
  • 3
  • 22
  • 35