I've got an AppCompatActivity which is the main View of the app. There I've got an OptionsMenu with a button to display a drawer menu and another button to filter the results (Because each MenuItem in the drawer are different Listfragments).
What I need to accomplish is, when clicking the filter button on the OptionsMenu, open a fragment with all the filtering criteria.
So this is the code managing the explained above:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_menu:
if (drawer.isDrawerOpen(GravityCompat.START)) {
hideDrawer();
} else {
showDrawer();
}
return true;
case R.id.action_filter:
fragmentManager = getFragmentManager();
fragment = new FilterFragment();
args.putInt("idList", idList);
fragment.setArguments(args);
fragmentManager.beginTransaction().replace(R.id.drawer_layout, fragment).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Doing that the Fragment shows up and then I get a NPE:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TableRow.setVisibility(int)' on a null object reference
Fragment onCreateViewMethod
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
getActivity().invalidateOptionsMenu();
skbrDays = getActivity().findViewById(R.id.seekBar);
daysLostRow = getActivity().findViewById(R.id.daysLostRow);
genderRow = getActivity().findViewById(R.id.genderRow);
locationRow = getActivity().findViewById(R.id.locationRow);
rgupGender = getActivity().findViewById(R.id.rgupGender);
rgupType = getActivity().findViewById(R.id.rgupType);
btnBreed = getActivity().findViewById(R.id.btnBreed);
recyclerView = getActivity().findViewById(R.id.recyclerView);
daysLostRow.setVisibility(View.VISIBLE);
return inflater.inflate(R.layout.activity_filter, container, false);
}
Ok, so I'm getting the NPE because getActivity() is returning null. And now I have to guess, not really knowing the reason, that is beacuse I'm not replacing the fragment on onCreate method from the activity?
If that is the reason how can I achieve the same result calling the fragment from onCreate?