android – Own toolbar for each Fragment

Question:

I use several fragments for which there is a separate toolbar. When adding a toolbar, the error "activity.getSupportActionBar.setTitle () may produce java.nullpointerexeption" is highlighted in the studio. In this case, the fragment is loaded, but all actions are stuck, it does not go to other fragments. Please tell me what is the error?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_three,container,false);
    Toolbar profile_toolbar = (Toolbar)view.findViewById(R.id.profile_toolbar);
    AppCompatActivity activity = (AppCompatActivity)getActivity();
    activity.getSupportActionBar().setTitle("dgdfg");
return view;
}

UPD. The error lay in the use of FragmentTabHost, for some reason the view with the fragment was stuck on the fragment using the toolbar. Had to replace FragmentTabHost with TabHost

Answer:

This is not an error, but a warning from Android Studio . under certain conditions, the getSupportActionBar() method can return null and then a NullPointerException will already happen in your application. To exclude this, it is enough to check for null . Then the studio will stop scaring you with this message.

ActionBar actionBar = activity.getSupportActionBar();
if(actionBar!= null) {
    //какой то код
}

Because of this, your fragments most likely stick, tk. you only found the ToolBar but didn't install it, so getSupportActionBar() returns null . Try it like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_three,container,false);
    Toolbar profile_toolbar = (Toolbar)view.findViewById(R.id.profile_toolbar);
    AppCompatActivity activity = (AppCompatActivity)getActivity();
    activity.setSupportActionBar(profile_toolbar);
    ActionBar actionBar = activity.getSupportActionBar();
    if(actionBar!= null) {
        actionBar.setTitle("dgdfg");
    }
    return view;
}
Scroll to Top