Android Navigation Toolbar Profile Fragment

  • Replies:1
  • OpenNot stickiedUnanswered
  • Forum posts: 1

Apr 14, 2016 11:35:28 PM via Website

I'm very new to Android Development, and I've been playing around with the default Navigation Toolbar template that Android Studio provides. I've posted this question in Stack Overflow, but I'm hoping that maybe I'll get a response here, in a forum for Android Development.

I've followed tutorials online with regards to how to set up fragments for the elements of the menu. So for the camera, gallery, etc. I'm able to switch to the fragment I want. However, I also want to make the green profile picture area also switch to the proFragment (profile fragment) when it's clicked (this is under the nav_header_main.xml file), but I can't seem to figure out how to. I have an id set for that section, and I try to reference it like the template did when it referenced the floating action button:

    LinearLayout user= (FloatingActionButton) findViewById(R.id.user_layout);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        proFragment fragment = new proFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

});

However, my app crashes and spits out the error:

   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.testApp/com.example.android.testApp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

I've also tried putting an invisible button over the area, but I keep getting

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.testApp/com.example.android.testApp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

I'm confused to why I'm referencing a null object - is it because the green user profile header hasn't been created yet? How can I get around this? Thanks for all the help!!

  • Forum posts: 1

Apr 17, 2016 12:03:13 AM via Website

There are a few things in your code that I think are problems. But the main one I think you've already identified.

Create your fragment first, then after try and set the on click listener. This is why you are getting a null reference exception; the object is null because it doesn't exist.

Second, im a bit confused by why you are setting your on clicklistener on 'fab' instead of 'user'. You just declared 'user' as type floating action button so I'm assuming you actually mean to set the clicklistener this.