Al Hennessey
Al Hennessey

Reputation: 2445

NullPointerException when referencing toolbar in fragment

I have added a toolbar in my activity and am trying to access it in my fragment to change the title and icon for the back navigation, however i keep getting the error

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference

When i run my app as well as a number of warnings about possible object being null. I know it has something to do with getsupportactionbar however i cannot work out what i am doing wrong

Here is the code for declaring the toolbar in activity

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

The code for referencing and changing the toolbar in fragment

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

And the code for declaring the toolbar in xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorAccent"
    android:layout_alignParentTop="true"
    app:popupTheme="@style/AppTheme.PopupOverlay" />

I am using appcompatactivity if it helps

Upvotes: 0

Views: 991

Answers (3)

Pooya
Pooya

Reputation: 6136

I think the problem is that you access the toolbar before view inflation which results in NullPointerException. And also since you are using support library you need to cast your toolbar to android.support.v7.widget.Toolbar. Here is a solution which may help:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) rootView.findViewById(R.id.toolbar);
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);    

        return rootView;
}

Upvotes: 3

BRG
BRG

Reputation: 380

Modify this:

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

to this:

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setDisplayShowHomeEnabled(true);
getActivity().setSupportActionBar(toolbar);

Hope it helps!!!

Upvotes: -1

Rocky Zhang
Rocky Zhang

Reputation: 1320

((Activity)getActivity()).setSupportActionBar(toolbar);

Upvotes: -1

Related Questions