Search code examples
androidtextviewandroid-navigationview

App crashes when accessing multiple textviews from navigation header


recently i tried an app with navigation view with header. the header contains 2 textview, a name and email. When i tried to setText the textview dynamically through code,it throws null pointerexception.

Can anyone please help me to resolve this problem.

Navigation_view

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/activity_home_drawer" />

Navigation_header

 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="@dimen/nav_header_height"
        android:gravity="bottom"
        android:orientation="vertical"
        android:theme="@style/ThemeOverlay.AppCompat.Dark">
     <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/imageView"
            android:paddingTop="@dimen/nav_header_vertical_spacing"
            android:layout_marginLeft="20dp"
            android:textColor="@color/colorAccent"
            android:text="Welcome"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

        <TextView
            android:id="@+id/email"
            android:layout_below="@+id/title"
            android:layout_marginLeft="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="[email protected]" />
    </RelativeLayout>

Code in MainActivity

    TextView Title = (TextView)findViewById(R.id.title);
            Title.setText("Guest");
TextView Email = (TextView)findViewById(R.id.email);
            Email.setText("[email protected]");

Logcat Error

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

Solution

  • As it's in the NavigationView

    try navigationView.findViewById(viewId);

    A strange thing I faced while I am using NavigationView is sometimes navigationView.findViewById(viewId) return null (reason may be we try to access (header) view before they are inflated to NavigationView)

    Now I used to add manually header to NavigationView

        View header = LayoutInflater.from(this).inflate(R.layout.header_layout, null);
        navigationView.addHeaderView(header);
    
        TexView title = (TextView) header.findViewById(R.id.title);