I'm trying to implement a navigation drawer with NavigationView
.
Everthing works fine so far, every item is displayed correctly. However there is a NullPointerException
in this lines :
View header = navigationView.getHeaderView(0);
TextView username = (TextView) header.findViewById(R.id.profile_name_id);
username.setText(mUser.getUsername());
In this line username.setText(mUser.getUsername());
the NullPointerExption is thrown. The strange thing is that it still displays the correct text of mUser.getUsername()
This is the NavigationView:
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/drawer"/>
Drawer_header:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:paddingTop="20dp"
android:paddingBottom="20dp"
android:background="@color/primary_dark"
android:layout_width="match_parent"
android:layout_height="160dp">
<ImageView
android:id="@+id/profile_pic_id"
android:src="@drawable/account_big"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:layout_height="0dp"/>
<android.widget.TextView
android:id="@+id/profile_name_id"
android:textColor="@color/primary_text"
android:textSize="18sp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Drawer:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/home_id"
android:checked="false"
android:icon="@drawable/home"
android:title="@string/home" />
<item
android:id="@+id/create_set_id"
android:checked="false"
android:icon="@drawable/add_box"
android:title="@string/create_learnset" />
<item
android:id="@+id/logout_id"
android:checked="false"
android:icon="@drawable/logout"
android:title="@string/logout" />
</group>
</menu>
You need to only write
Text View
.
Change this
<android.widget.TextView
android:id="@+id/profile_name_id"
android:textColor="@color/primary_text"
android:textSize="18sp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
To this.
<TextView
android:id="@+id/profile_name_id"
android:textColor="@color/primary_text"
android:textSize="18sp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
It's Done.