Null reference on ActionBar when calling it via getActivity() within a fragment in android studio

Viewed 30

In Android Studio, I am trying to call getActivity().getActionBar() to display the back button on the Action bar in a specific fragment only. Below is my code:

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
    getActivity().getActionBar().setDisplayShowHomeEnabled(true);
    
    View view=inflater.inflate(R.layout.fragment__two, container, false);
    return view;

}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        requireActivity().onBackPressed();
    }
    return super.onOptionsItemSelected(item);
}

Please tell me what I am doing wrong here! I want to set up back button in the action bar of this fragment only. Help me to figure it out, thanks!

1 Answers

Well you can try getting actionBar using:

ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();

NOTE: Do this after view is created i.e. inside onViewCreated() function like:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ActionBar actionBar = ((AppCompatActivity) requireActivity()).getSupportActionBar();
}
Related