Bruce Bruce - 3 years ago 181
Android Question

Null Object error when trying to set up navigation view listener

I am trying to setup a click listener in my menu which inside of a navigation view inside a fragment- I want to set the listener inside of my fragment as well

I am getting the error

"Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference"


When I try to run this code

public class FragmentNavigationDrawer extends Fragment implements NavigationView.OnNavigationItemSelectedListener {



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
return inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
}


Anyone know how to solve this issue? thanks

Answer Source

Try below code. Replace getACtivity with getView()

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    return inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
}

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

 NavigationView navigationView = (NavigationView) getView().findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download