即使在给出正确的引用之后也获得nullpointerexception。请看细节

时间:2016-04-21 04:13:09

标签: java android nullpointerexception navigation-drawer android-navigationview

我正在尝试从数据库中提取后在NavigationView中设置名称和电子邮件。

以下是我在NavigationView方法中引用onCreate()的方法:

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) 

请告诉我这里有什么问题。

抱歉,问题格式不正确。我还是初学者。

2 个答案:

答案 0 :(得分:1)

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

为了防止出现这样的错误,为了更好地维护代码,可以使用ButterKnife库。这很简单易用。

onCreate()方法调用Butterknife.bind()

并初始化任何View个对象执行以下操作:

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

希望这有帮助。

参考Butterknife

答案 1 :(得分:0)

添加以下行:

查看标题= navigationView.getHeaderView(0);

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