Reputation: 65
Hello I have Implemented a activity where i used navigation drawer.Its work fine but sometimes app is crashing because of actionbar.it throw nullpointerexception
I called fragment as follows
Upvotes: 1
Views: 143
Reputation: 28229
You can't call getActivity
from onCreateView
, as it may return null
, if the Activity
isn't attached yet to the Fragment
.
Activities
and Fragments
have separate lifecycles, getActivity
can be null while your fragment is in process of preparation.
You can move your code that depends on getActivity
to the Fragment.onActivityCreated(Bundle) callback.
Note that it is called after onCreateView
.
See more info here: https://developer.android.com/guide/components/fragments.html#CoordinatingWithActivity
UPDATE: As requested, here's a fixed code - I just split some of your onCreateView method into onActivityCreated
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
person = new Person();
str = person.getFragment();
view = inflater.inflate(R.layout.fragment_product_list, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
cd = new ConnectionDetector(getActivity());
parent = (AppCompatActivity) getActivity();
if (getArguments() != null) {
title = getArguments().getString("Title");
if (title != null) {
parent.getSupportActionBar().setTitle(title);
}
}
}
Upvotes: 1