即使在给出正确的引用后也会出现 nullpointerexception。请查看详情

Getting nullpointerexception even after giving right reference. Please see details

我试图在 NavigationView 中设置姓名和电子邮件,然后从数据库中获取它。

以下是我如何在 onCreate() 方法中给出 NavigationView 的参考:

navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

但是,我仍然收到此错误:Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.design.widget.NavigationView.getHeaderView(int)' on a null object reference at com.abc.xyz.MainActivity.fetchDataFromProviderProvided(MainActivity.java:689)

这是fetchDataFromProviderProvided()方法:

public void fetchDataFromProviderProvided() {
        if (authData != null) {
            swipeRefreshLayout.setRefreshing(false);
            if (authData.getProvider().equals("google")) {
                fetchDataFromGoogle();
            } else if (authData.getProvider().equals("facebook")) {
                onFacebookAccessTokenChange(AccessToken.getCurrentAccessToken());
            } else {

                // DO SOMETHING TO FETCH USER'S NAME

                String Uid = authData.getUid();

                Log.d("Uid:", Uid);

                Firebase userNameRef = mFirebaseRef.child(Uid + "/userName");

                Log.d("userName", String.valueOf(userNameRef));

                emailImage = (String) authData.getProviderData().get("profileImageURL");

                // error on the line below
                View imageView = navigationView.getHeaderView(0);
                //
                userImage = (ImageView) imageView.findViewById(R.id.userImage);

                new emailProfilePicAsync().execute(authData.getUid());

                View nameView = navigationView.getHeaderView(0);
                userName = (TextView) nameView.findViewById(R.id.userName);

                userNameRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        userName.setText(String.valueOf(dataSnapshot.getValue()));
                    }

                    @Override
                    public void onCancelled(FirebaseError firebaseError) {

                    }
                });

                emailName = userNameText;
                emailEmail = (String) authData.getProviderData().get("email");

                View emailView = navigationView.getHeaderView(0);
                userEmail = (TextView) emailView.findViewById(R.id.userEmail);
                userEmail.setText(emailEmail);

//                System.out.println(post.getUserName());
//                System.out.println(post.getUserEmail());
            }

            dataLoadingCompleteProgressDialog = ProgressDialog.show(MainActivity.this, "",
                    "Fetching user's info...", true);

            if (dataLoadingCompleteProgressDialog.isShowing()) {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        checkIfDataIsFetched();
                        dataLoadingCompleteProgressDialog.dismiss();
                    }
                }, 5500);
            }

        } else {

        }
    }

这里是 activity_main.xml 文件的代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    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="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        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_main"
        app:menu="@menu/activity_main_drawer"/>

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

这是完整的堆栈跟踪:

FATAL EXCEPTION: main
                                                                               Process: com.abc.xyz, PID: 19072
                                                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abc.xyz/com.abc.xyz.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.design.widget.NavigationView.getHeaderView(int)' on a null object reference
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                   at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.design.widget.NavigationView.getHeaderView(int)' on a null object reference
                                                                                   at com.abc.xyz.MainActivity.fetchDataFromProviderProvided(MainActivity.java:694)
                                                                                   at com.abc.xyz.MainActivity.onCreate(MainActivity.java:217)
                                                                                   at android.app.Activity.performCreate(Activity.java:6237)
                                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                                   at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                   at android.os.Looper.loop(Looper.java:148) 
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

请让我知道这里出了什么问题。

抱歉,问题格式错误。我还是初学者。

确保在调用方法 fetchDataFromProviderProvided() 完成之前初始化 navigationView

为防止此类错误并提高代码的可维护性,请使用 ButterKnife 库。这使用起来非常简单。

onCreate() 方法调用 Butterknife.bind() 中初始化任何 View 对象执行以下操作:

@Bind(R.id.nav_view)
NavigationView navigationView;

希望对您有所帮助。

引用Butterknife

添加这一行:

查看页眉 = navigationView.getHeaderView(0);

navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);