Hammad Nasir Hammad Nasir - 7 months ago 126
Java Question

Getting nullpointerexception even after giving right reference. Please see details

I'm trying to set the name and email in

NavigationView
after fetching it from the database.

Here's how I have given reference of
NavigationView
in
onCreate()
method:

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


But, I'm still getting this error:
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)


Here's
fetchDataFromProviderProvided()
method:

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 {

}
}


Here's
activity_main.xml
file's code:

<?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>


Here's complete stacktrace:

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) 


Please let me know what's wrong here.

Sorry, for bad formatting of the question. I'm still a beginner here.

Answer

Make sure, you Initialise the navigationView before the call for method fetchDataFromProviderProvided() is done.

To prevent such Mistakes, and for better Maintainability of code make use of the ButterKnife library. This is pretty simple to use.

in onCreate() method call Butterknife.bind() and to initialise any View Objects do the following :

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

Hope this helps.

Reference Butterknife

Comments