Search code examples
androidandroid-listfragment

getListAdapter() from ListFragment returns null, getListView works


As per title, I'm stuck in this absurd problem

I've got a ListFragment, here's the stripped down code:

public class AlarmsListFragment extends ListFragment implements AbsListView.OnItemClickListener {
    public ListAdapter mAdapter;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setRetainInstance(true);

        mAdapter = new AlarmsAdapter(getActivity(), R.layout.alarm_card_item, alarmsList);
    }
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_alarms_list, container, false);

        mListView = (AbsListView) view.findViewById(android.R.id.list);
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(this);

        return view;
    }
}

And then there's an activity:

public class MainActivity extends Activity implements AlarmsListFragment.OnAlarmSelectedListener {
ListFragment mAlarmsListFragment;
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fm = getFragmentManager();
        mAlarmsListFragment = (ListFragment) fm.findFragmentByTag(ALARM_LIST_TAG);
        if (mAlarmsListFragment == null)
        {
            mAlarmsListFragment = new AlarmsListFragment();
            getFragmentManager().beginTransaction()
                    .add(R.id.listContainer, mAlarmsListFragment, ALARM_LIST_TAG)
                    .commit();
        }
    }

Later on, onOptionsItemSelected, I've got some code that needs to add an item to the ListAdapter and invalidate the previous List, so I'm calling:

AlarmsAdapter mAdapater = (AlarmsAdapter) mAlarmsListFragment.getListAdapter();
mAdapater.add(a);
mAdapater.notifyDataSetChanged();

Thing is, I get a nullPointerException because getListAdapter() returns null, while getListView() works fine.. what might be causing this bug?


Solution

  • You need to call setListAdapter on your ListFragment,ie:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setRetainInstance(true);
    
        mAdapter = new AlarmsAdapter(getActivity(), R.layout.alarm_card_item, alarmsList);
    
        setListAdapter(mAdapter);
    }
    

    You do not need to call setAdapter on your ListView. The ListFragment will handle it.