I’m occasionally getting a NullPointerException in my ArrayAdapter that populates my ListFragment. It appears that getActivity() is returning null, but as far as I can tell it shouldn’t do that.
Adapter code inflater = (LayoutInflater)... is the exception line:
@Override
public View getView( int position, View convertView, ViewGroup parent )
{
view = convertView;
if ( view == null )
{
/* Inflate a row */
inflater = (LayoutInflater)getActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE ); // THIS IS THE EXCEPTION LINE
view = inflater.inflate( R.layout.pairing_list_row, parent, false );
}
I’m using a Loader to get the data, and I don’t init that until the onActivityCreated method. The adapter isn’t created until the loader is finished loading, so it should never happen prior to onActivityCreated.
@Override
public void onActivityCreated( Bundle savedInstanceState )
{
super.onActivityCreated( savedInstanceState );
getLoaderManager().initLoader( 0, null, this );
}
@Override
public void onLoadFinished( Loader<Cursor> loader, Cursor cursor )
{
PairingArrayAdapter pairings = (PairingArrayAdapter)getListAdapter();
if ( pairings == null )
{
pairings = new PairingArrayAdapter( getActivity(), R.layout.pairing_list_row );
setListAdapter( pairings );
}
...
Any ideas on what’s causing the NullPointerException? It doesn’t happen all the time, it happens once, I do the same thing again and it doesn’t happen. I can’t figure it out.
I’ve determined that the only possible explanation is that the
FragmentStatePagerAdapterthat I’m using causesonLoadFinishedto be called when the Fragment is detached in certain circumstances, thus necessitating a check for an attached activity when runninggetView.