Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getActivity null exception warning?

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 ?

like image 209
DavDeveloper Avatar asked Oct 15 '18 17:10

DavDeveloper


2 Answers

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

like image 143
Hocine B Avatar answered Sep 27 '22 19:09

Hocine B


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

like image 40
Rodrigo Ezequiel Arias Roberts Avatar answered Sep 27 '22 17:09

Rodrigo Ezequiel Arias Roberts