Adam
Adam

Reputation: 67

Using a Loader in a Fragment causes a NullPointerException

I'm using a android.support.v4.content.Loader in a android.support.v4.app.Fragment and sometimes I get a

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.content.Loader.abandon()' on a null object reference

This is my first time using a loader and I'm not 100% sure how they work. I also want the loader to refresh data every minute, so I'm using a handler and runnable to call loaderManager.restartLoader() every minute. (If that's not what you're supposed to do, I'm open to better ideas)

So far I have the Runnable as a global variable:

private Runnable mStatusChecker = new Runnable() {
    @Override
    public void run() {
            refresh();
    }
};

which calls the refresh() function:

public void refresh() {
    if (MainActivity.isConnected) {
        loaderManager.restartLoader(LOADER_ID, null, this);
    }
}

That line of code, loaderManager.restartLoader, sometimes throws the exception (although sometimes it works).

In OnCreateView I initialize the loader and the handler

   View rootView = inflater.inflate(R.layout.layout_for_fragments, container, false);


    loaderManager = getLoaderManager();

    if (MainActivity.isConnected) {
        loaderManager.initLoader(LOADER_ID, null, this);
    }

    adapter = new CustomArrayAdapter(getActivity().getApplicationContext(), exchanges, R.color.colorPrimaryDark);

    listView = rootView.findViewById(R.id.list);


    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Exchange exchange = exchanges.get(i);
            String url = exchange.getUrl();
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(browserIntent);

        }
    });

    listView.setAdapter(adapter);


    mHandler = new Handler();
    mHandler.postDelayed(mStatusChecker, refreshRate);


    setHasOptionsMenu(true);


    return rootView;

and the onCreateLoader method is

public Loader onCreateLoader(int i, Bundle bundle) {

    String[] strings = {QUADRIGA_BTC};

    if (isAdded()){
        return new BLoader(getActivity(), strings);
    }
    return null;
}

I have 4 very similar fragments that all have a similar loader, and the fragments are managed by a tablayout and viewpager.

Upvotes: 0

Views: 315

Answers (1)

Adam
Adam

Reputation: 67

I think I figured out the issue. Removing callbacks from the Runnable in onStop() seems to have fixed it. My changes:

@Override
public void onStop() {
    super.onStop();
    mHandler.removeCallbacks(mStatusChecker);
} 

Upvotes: 1

Related Questions