user1166862 user1166862 - 2 months ago 17
Android Question

Adding code for TextView item in Navigation Drawer header

I currently have a Navigation Drawer implemented inside my app using

NavigationView
. The layout of the drawer is split into a header
drawer_header.xml
and a menu
drawer_menu.xml
. It looks something like this:

Drawer

I am trying to set the user's name
DrawerNameTv
in the header in java code using
setText
instead of
xml
however I receive the following error:


java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference


Here's the
Main_Activity.java


TextView DrawerName;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);

CustomToolbar = (Toolbar) findViewById(R.id.toolbar);
DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView = (NavigationView) findViewById(R.id.navigation_view);
DrawerName = (TextView) findViewById(R.id.DrawerNameTv);

DrawerName.setText("Test");

...


And the
drawer_header.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/user_pic" />

<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:textSize="20dp"
android:layout_marginTop="120dp"
android:id="@+id/DrawerNameTv" />

</RelativeLayout>


Pardon me as I'm new to Android development.

Answer

The view DrawerNameTv is not found in the layout you're referring to and that's why its giving you a NullPointerException. You need to find the DrawerNameTv inside your NavigationView like this.

Inside your onCreate function

// lets change the variable names first.
private NavigationView mNavigationView;

mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
DrawerName = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.DrawerNameTv);

// Now set the text here
DrawerName.setText("Test");