here is my layout file which is a part of navigation bar header->
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="250dp"
android:background="@color/white">
<ImageView
android:id="@ id/drawerProfileImage"
android:layout_width="163dp"
android:layout_height="157dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="@drawable/linus_trovalds"
android:src="@drawable/linus_trovalds"/>
<TextView
android:id="@ id/drawerEmailId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="16dp"
android:text="[email protected]"
android:textColor="@color/gray"
android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/drawerProfileImage" />
</androidx.constraintlayout.widget.ConstraintLayout>
now in my onCreate method i am trying to change its text but i get an error.
onCreate method code->
//change email id in drawer
val drawerEmailIdValue = "[email protected]"
val drawerEmailId = findViewById<TextView>(R.id.drawerEmailId)
drawerEmailId.text = drawerEmailIdValue //not working for some reason
now here is the error->
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.eater/com.example.eater.DishList}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
can someone help with what is going on?
CodePudding user response:
you can't access the drawerEmailId directly as this is not part of activity's xml instead it's inside navigation view.
val navigationView = findViewById<NavigationView>(R.id.nav_view) // nav_view is id for NavigationView
val email = navigationView.getHeaderView(0).findViewById<TextView>(R.id.drawerEmailId)
email.text = "[email protected]"
you can do it like above it will get the email TextView from header view.
CodePudding user response:
Your code is correct, the issue is where you're calling it. If you're using a Fragment, you should be placing this code inside the onViewCreated()
method and if you're using an Activity, this should go inside the onCreate()
method.
Also, I'd recommend looking into ViewBinding as that is the suggested approach.