Anjum Anjum - 2 months ago 15
Java Question

How to set text in textView which is in NavigationView

I am getting null pointer exception while setting text in textview. textview is in navigation view in dashboard activity.

In main activity, i am trying to set text like this :

public class Dashboard extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
TextView StudentNameView = (TextView) navigationView.findViewById(R.id.studentName);
StudentNameView.setText("Test");
}
}


Here is my dashboard activity's xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:fitsSystemWindows="true" tools:openDrawer="start">

<include layout="@layout/app_bar_dashboard" android:layout_width="match_parent"
android:layout_height="match_parent" />

<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_dashboard"
app:menu="@menu/activity_dashboard_drawer" />

</android.support.v4.widget.DrawerLayout>


And my navigation header menu is

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark" android:orientation="vertical"
android:gravity="bottom">



<TextView android:layout_width="match_parent" android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing" android:text=""
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
android:id="@+id/studentName"
/>

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="" android:id="@+id/studentEmail" />

</LinearLayout>

Answer

More important is to use lib version v7:23.1.1 use compile 'com.android.support:appcompat-v7:23.1.1'

In your code write following lines

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View v = navigationView.getHeaderView(0);
TextView avatarContainer = (TextView ) v.findViewById(R.id.imgAvatar);
Comments