Search code examples
androidandroid-fragmentsfragmentandroid-nested-fragment

NullPointerException LayoutInflater.from(context) - Fragment Android


I have implement Nested Fragments. Child fragment contains BaseAdapter. When I switching(replace) child fragments then I am getting Nullpointer exception. Code:

public MyAdapter(final Context context,
            final List<CusomObject> CusomObjectList) {
        mInflater = LayoutInflater.from(context);
        this.CusomObjectList = CusomObjectList;     
    }

I am getting error in this line - mInflater = LayoutInflater.from(context);

I passed getActivity() in MyAdapter constructor from Fragment.

Code:

adapter = new MyAdapter(getActivity(), customList);
listView.setAdapter(adapter);

Solution

  • I passed getActivity() in MyAdapter constructor from Fragment.

    that's extactly the problem.

    when Fragment constructor is called - the reference to the Activity is still not initiated.

    instead - you should do any object creations or initializations that depends on Activity context from the Fragment's onCreate() method.

    in general, it's not recommended at all to override Fragment constructor, exactly like that you don't override Activity constructor, but only it life-cycle callbacks.

    more info in - http://developer.android.com/guide/components/fragments.html