Reputation: 215
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);
Upvotes: 3
Views: 1308
Reputation: 10785
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
Upvotes: 5
Reputation: 18933
Use another variable.
Context mContext;
public MyAdapter(final Context context,
final List<CusomObject> CusomObjectList) {
this.mContext = context;
mInflater = LayoutInflater.from(mContext);
this.CusomObjectList = CusomObjectList;
}
Upvotes: 0