This is my XML code (activity_homepage.xml):
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="@ id/nav_view"
app:headerLayout="@layout/nav_header"
app:menu="@menu/drawer_menu"/>
nav_header.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="176dp"
android:background="@color/design_default_color_primary_dark"
android:gravity="bottom"
android:padding="16dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:layout_width="68dp"
android:layout_height="58dp"
android:layout_marginBottom="10dp"
android:src="@drawable/ic_action_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:text="Null"
android:id="@ id/user"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"
android:paddingLeft="8dp"/>
</LinearLayout>
And this is my java code:
@Override
TextView txt;
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
txt = findViewById(R.id.user);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("Name");
txt.setText(value); //throws NullPointerException
}
}
I've double checked the id
, it's correct. Then why the NullPointerException
?
EDIT: Tried to fetch the header from the navigation view like this:
NavigationView navigationView = findViewById(R.id.nav_view);
View header = navigationView.getHeaderView(1);
txt = header.findViewById(R.id.user);
I still get NPE in the line navigationView.getHeaderView(1);
CodePudding user response:
navigationView.getHeaderView( 0 );
How about 0 ?
CodePudding user response:
I had done such a silly mistake :p
I tried fetching the header before setContentView()
. That's why I was getting NPE. The following code resolved the issue:
setContentView(R.layout.activity_homepage);
NavigationView navigationView = findViewById(R.id.nav_view);
View header = navigationView.getHeaderView(0);