I'm new to fragments and I'm trying to take an activity and convert it to a fragment. A lot of the stuff I'm using needs Context and when I use getActivity() I get a log of warnings that it may return null and I'm not sure how to fix it. I read that I should attach the fragment to the activity somehow, but I'm not sure. I'm basically using one activity and going to have 4 fragments because I want to use a navigation drawer.
This is in the main activity for showing the fragments
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_calendar:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new CalendarFragment()).commit();
break;
case R.id.nav_survey:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new SurveyFragment()).commit();
break;
case R.id.nav_forum:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ForumFragment()).commit();
break;
case R.id.nav_logout:
logout();
break;
case R.id.nav_contact:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ContactFragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
And in the fragments onCreateView() I have this, I have a lot of methods and most of them use Context, I added the if statement because of the same warning and that seemed to work there but how should I take care of the rest on Context uses. I don't see making an if statement for each time a good thing.
View view = inflater.inflate(R.layout.fragment_calendar, container, false);
if (getActivity() != null) {
((MainActivity) getActivity()).getSupportActionBar().setTitle(R.string.calendar);
}
AndroidThreeTen.init(getActivity());
initialBuild(view);
buildCalendarView();
setRecyclerView();
return view;
Edit
Related images