Marcos Miguez
Marcos Miguez

Reputation: 115

Android NullPointerException getActivity()

Im having one bug in my app. It's caused because I'm on a Fragment, and the method getActivity returns null. The problem is: I'm checking the method first.

How it should be happening?

public void refreshDataList() {
    if(getActivity() != null && !getActivity().isFinishing()) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(swipeContainer != null) {
                    swipeContainer.setRefreshing(false);
                }
            }
        });
    }

The error is happening in this line:

    getActivity().runOnUiThread(new Runnable() {


Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'void android.app.Activity.runOnUiThread(java.lang.Runnable)' on a null object reference

There's something that I'm forgetting?

Upvotes: 0

Views: 214

Answers (1)

Venkata Narayana
Venkata Narayana

Reputation: 1697

Did you try referencing the activity instance to another variable and using the same variable for checking as well as posting runnables like below?

public void refreshDataList() {
    Activity activity = getActivity();
    if(activity != null && !activity.isFinishing()) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(swipeContainer != null) {
                    swipeContainer.setRefreshing(false);
                }
            }
        });
    }

Upvotes: 1

Related Questions