Вид навигации кажется нулевым

У меня есть это представление навигации в навигационном ящике, в котором я пытаюсь установить некоторый текст для нескольких TextView, которые у меня есть в моем представлении навигации. Дело в том, что в других активностях работало отлично, а в этой как-то не корректно. Ошибка появляется, когда я вызываю метод setNavigationDrawer и пытаюсь установить текст для компонентов представления навигации.

06-07 18:37:36.658 16792-16792/pds.pdsandroid E/AndroidRuntime: FATAL EXCEPTION: main
                                                            Process: pds.pdsandroid, PID: 16792
                                                            java.lang.RuntimeException: Unable to start activity ComponentInfo{pds.pdsandroid/pds.pdsandroid.Perfil}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                at android.os.Looper.loop(Looper.java:164)
                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                             Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                at pds.pdsandroid.Perfil.setNavigationDrawer(Perfil.java:109)
                                                                at pds.pdsandroid.Perfil.onCreate(Perfil.java:35)
                                                                at android.app.Activity.performCreate(Activity.java:6975)
                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
                                                                at android.os.Handler.dispatchMessage(Handler.java:105) 
                                                                at android.os.Looper.loop(Looper.java:164) 
                                                                at android.app.ActivityThread.main(ActivityThread.java:6541) 
                                                                at java.lang.reflect.Method.invoke(Native Method) 
                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

И это мой код:

package pds.pdsandroid;

public class Perfil extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

private CinematlasApp mCinematlasApp;

private ImageView nav_imatge;
private TextView nav_nom;
private TextView nav_username;
private TextView nav_correu;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private NavigationView navView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_perfil);

    mCinematlasApp = ((CinematlasApp)this.getApplication());
    setNavigationDrawer();

    ImageView mevaVista = (ImageView) findViewById(R.id.imageView_perfil);
    mevaVista.setImageResource(R.drawable.imatge_perfil);

    FillData(mCinematlasApp.getUser());

}

private void setNavigationDrawer(){
    mDrawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer);
    mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.Open,R.string.Close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    navView = (NavigationView)findViewById(R.id.navigation_view);
    navView.setNavigationItemSelectedListener(this);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    //SharedPreferences mSettings = getSharedPreferences(APP_SHARED_PREFERENCES, Context.MODE_PRIVATE);

    User user = mCinematlasApp.getUser();
    nav_imatge = (ImageView)findViewById(R.id.navDrawer_imgPerfil);
    nav_nom = (TextView)findViewById(R.id.navDrawer_nom);
    nav_username = (TextView)findViewById(R.id.navDrawer_username);
    nav_correu = (TextView)findViewById(R.id.navDrawer_correu);

    nav_nom.setText(user.name+" "+user.surnames);
    nav_username.setText(user.username);
    nav_correu.setText(user.email);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Intent intent = null;
    switch(item.getItemId()){
        case R.id.drawer_home:
            intent = new Intent(Perfil.this,Home.class);
            break;
        case R.id.drawer_perfil:
            intent = new Intent(Perfil.this,Perfil.class);
            break;
        case R.id.drawer_llistes:
            intent = new Intent(Perfil.this,Llistes.class);
            break;
        case R.id.drawer_sortir:
            mCinematlasApp.logout();
            intent = new Intent(getApplicationContext(),Login.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            break;
    }
    if(intent!=null){
        startActivity(intent);
        if(!mCinematlasApp.isLogged())
            finish();
    }
    return true;
}
}

Это мой XML-файл тела:

<android.support.constraint.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:id="@+id/mainLayout"
    android:layout_height="match_parent" android:layout_width="match_parent">

<!--IMATGE TOP-->
<android.support.constraint.ConstraintLayout android:layout_width="wrap_content"
                                             android:layout_height="220dp" android:id="@+id/layout_imatgeTop"
>
    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/atat"
            android:scaleType="centerCrop"
    />

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/filtre8"
            android:alpha="0.4"
            android:scaleType="centerCrop"
    />
</android.support.constraint.ConstraintLayout>
<!--PERFIL PRINCIPAL-->

<LinearLayout android:layout_width="0dp"
              android:layout_height="0dp"
              app:layout_constraintTop_toTopOf="@+id/layout_imatgeTop"
              android:layout_marginTop="219dp"
              android:background="@color/cinematlas_backgroundLightGrey"
              android:gravity="center"
              app:layout_constraintRight_toRightOf="parent"
              app:layout_constraintLeft_toLeftOf="parent"
              app:layout_constraintHorizontal_bias="0.0"
              app:layout_constraintBottom_toBottomOf="parent"
              android:layout_marginBottom="0dp"
              app:layout_constraintVertical_bias="0.0"
              android:orientation="vertical"
              android:id="@+id/layout_main">
    <!--NOM-->
    <LinearLayout android:layout_width="match_parent" android:layout_height="40dp"></LinearLayout>

    <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"
                  android:orientation="vertical"
                  android:gravity="center"
                  android:background="@drawable/layout_bg"
    >
        <TextView
                android:layout_marginTop="10dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Nom"
                android:textStyle="bold"
                android:id="@+id/nom" android:contentDescription="nom" tools:text="nom"
        />

        <TextView
                android:layout_marginTop="5dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/drawable_back_textview2"
                android:id="@+id/nom_passat" android:contentDescription="nom_passat" tools:text="nom_passat"
        />


        <!--COGNOMS-->


        <TextView
                android:layout_marginTop="5dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Cognoms"
                android:textStyle="bold"
                android:id="@+id/cognoms" android:contentDescription="Cognoms" tools:text="Cognoms"
        />

        <TextView
                android:layout_marginTop="5dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/drawable_back_textview2"
                android:id="@+id/cognoms_passat" android:contentDescription="cognoms_passat"
                tools:text="cognoms_passat"
        />


        <!--NICKNAME-->


        <TextView
                android:layout_marginTop="5dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Nom d'usuari"
                android:textStyle="bold"
                android:id="@+id/nickname" android:contentDescription="nickname" tools:text="nickname"
        />

        <TextView
                android:layout_marginTop="5dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:background="@drawable/drawable_back_textview2"
                android:id="@+id/nickname_passat" android:contentDescription="nickname_passat"
                tools:text="nickname_passat"
        />


        <!--CORREU-->


        <TextView
                android:layout_marginTop="5dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Correu electrònic"
                android:textStyle="bold"
                android:id="@+id/correu" android:contentDescription="correu" tools:text="correu"
        />

        <TextView
                android:layout_marginTop="5dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:background="@drawable/drawable_back_textview2"
                android:id="@+id/correu_passat" android:contentDescription="correu_passat"
                tools:text="correu_passat"
        />


        <!--PAIS-->

        <TextView
                android:layout_marginTop="5dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="País"
                android:textStyle="bold"
                android:id="@+id/pais" android:contentDescription="pais" tools:text="pais"
        />

        <TextView
                android:layout_marginTop="5dp"
                android:layout_marginBottom="10dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/drawable_back_textview2"
                android:id="@+id/pais_passat" android:contentDescription="pais_passat" tools:text="pais_passat"
        />
    </LinearLayout>


</LinearLayout >
<!--IMATGE PERFIL-->
<android.support.constraint.ConstraintLayout android:layout_width="150dp"
                                             android:layout_height="150dp"
                                             app:layout_constraintRight_toRightOf="parent"
                                             app:layout_constraintLeft_toLeftOf="parent"
                                             app:layout_constraintTop_toTopOf="@+id/layout_imatgeTop"
                                             android:layout_marginTop="138dp" android:id="@+id/layout_imatgePerfil">
    <de.hdodenhof.circleimageview.CircleImageView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageView_perfil"
            app:civ_border_color="@color/cinematlas_secondaryDarkColor"
            app:civ_border_width="3dp" />
</android.support.constraint.ConstraintLayout>
<!--BOTO EDITAR-->
<android.support.v7.widget.AppCompatButton
        android:text="Editar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button_editar"
        android:layout_marginRight="16dp"
        app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="@+id/layout_imatgeTop"
        android:layout_marginTop="16dp"/>
<Button
        android:text="Sortir"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button_logout"
        app:layout_constraintBottom_toBottomOf="@+id/layout_main" android:layout_marginBottom="24dp"
        android:layout_marginLeft="0dp" app:layout_constraintLeft_toLeftOf="parent" android:layout_marginRight="0dp"
        app:layout_constraintRight_toRightOf="parent"/>

And this is my whole xml:

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

    <android.support.constraint.ConstraintLayout...>

    <android.support.design.widget.NavigationView android:layout_width="wrap_content"
                                                  android:layout_height="match_parent"
                                                  android:background="@color/colorBlanc"
                                                  app:itemTextColor="@color/cinematlas_secondaryDarkColor"
                                                  app:itemIconTint="@color/cinematlas_primaryDarkColor"
                                                  app:menu="@menu/menu_drawer"
                                                  android:layout_gravity="start"
                                                  android:id="@+id/navigation_view"
                                                  app:headerLayout="@layout/navigation_drawer_header"
    >

    </android.support.design.widget.NavigationView>

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

И мой код ящика навигации:

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="170dp"
 >

<!--BACKGROUND-->
<RelativeLayout android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/nav_background"
>
    <ImageView android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:background="@drawable/cinema"
               android:alpha="0.8"
    />

    <ImageView android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:background="#b18d6e63"
    />

</RelativeLayout>

<!--MAIN INFO-->
<LinearLayout android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:gravity="center"
              android:orientation="vertical"
              android:padding="20dp"
              android:layout_centerInParent="true">

    <de.hdodenhof.circleimageview.CircleImageView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:src="@drawable/imatge_perfil"
            android:layout_width="75dp"
            android:layout_height="75dp"
            android:id="@+id/navDrawer_imgPerfil"
            app:civ_border_color="@color/cinematlas_primaryLightColor"
            app:civ_border_width="2dp"/>

    <LinearLayout android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:orientation="horizontal"
                  android:layout_marginTop="8dp"

    >
        <TextView android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:id="@+id/navDrawer_nom"
                  android:textStyle="bold"
                  android:textColor="@color/cinematlas_secondaryDarkColor"
                  android:text="Nom"
        />

        <TextView android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:id="@+id/navDrawer_username"
                  android:textColor="@color/cinematlas_primaryTextColor"
                  android:text="Username"
                  android:layout_marginLeft="6dp"
        />
    </LinearLayout>


    <TextView android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/navDrawer_correu"
              android:textColor="@color/cinematlas_primaryTextColor"
              android:textStyle="italic"
              android:text="Correu electrònic"
              android:layout_marginTop="2dp"
    />


</LinearLayout>

Thanks for your help.


person maga    schedule 07.06.2018    source источник
comment
Пользователь user = mCinematlasApp.getUser(); может возвращать ноль   -  person Bäda    schedule 07.06.2018
comment
@Bäda Я уже проверил значения пользователя, и он не возвращает ноль. То же самое для navView, оно тоже не равно нулю.   -  person maga    schedule 07.06.2018
comment
Одна из этих переменных: nav_nom, nav_username, nav_correu возвращает значение null, проверьте свой xml   -  person Bita Mirshafiee    schedule 07.06.2018
comment
@maga можешь показать свой xml-файл?   -  person Bäda    schedule 07.06.2018
comment
@BitaMirshafiee Я обновил свой пост, но я не думаю, что это имеет какое-то значение, потому что я уже использовал этот точный код для другого действия.   -  person maga    schedule 07.06.2018
comment
@Bäda Я уже обновил его.   -  person maga    schedule 07.06.2018
comment
Если XML-код, который вы обозначили как код моего навигационного ящика, равен navigation_drawer_header, то вам нужно найти в нем View немного по-другому. Взгляните на этот пример.   -  person Mike M.    schedule 08.06.2018
comment
@maga вам нужно изменить nav_imatge = (ImageView)findViewById(R.id.navDrawer_imgPerfil); to nav_imatge = (CircleImageView)findViewById(R.id.navDrawer_imgPerfil);   -  person Bäda    schedule 08.06.2018


Ответы (2)


Только что узнал, что мне нужно было найти вид навигации View, чтобы «findViewById» вот так: View parentView = navView.getHeaderView(0);

Любопытно, что это произошло только в этом Activity. Я предполагаю, что из всех поисков у него просто не хватило времени для создания представления, поэтому он просто не смог найти: представления nav_x.

person maga    schedule 07.06.2018

проверьте идентификатор ваших текстовых представлений в xml с теми, которые вы использовали здесь:

nav_imatge = (ImageView)findViewById(R.id.navDrawer_imgPerfil);
nav_nom = (TextView)findViewById(R.id.navDrawer_nom);
nav_username = (TextView)findViewById(R.id.navDrawer_username);
nav_correu = (TextView)findViewById(R.id.navDrawer_correu);

Они не то же самое

person Bita Mirshafiee    schedule 07.06.2018
comment
Да, я только что опубликовал свой XML-файл навигационного ящика. - person maga; 07.06.2018
comment
Посмотрите на ошибку, которую вы показали нам в своем сообщении, это, безусловно, что-то не так с текстовым представлением, которое вы определили в своем xml, и его определением в вашей деятельности, попробуйте проверить это еще раз. - person Bita Mirshafiee; 07.06.2018
comment
Ну я до сих пор не могу понять, что это такое. - person maga; 08.06.2018
comment
navDrawer_imgPerfil - это круговое изображение, а не текстовое представление - person Bita Mirshafiee; 08.06.2018