简体   繁体   中英

Firebase: Getting Firebase Current User Crashes The App

I want to get current user id so I can pass it to Document Reference to update some data in the document.

So After login the app takes me to Home page and I put the following code there:

 userRef = db.document("users/"+mFirebaseAuth.getCurrentUser().getUid());

    userRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
            if(e != null){
                Log.w(TAG, "Listen Failed");
                return;
            }

            if(documentSnapshot != null && documentSnapshot.exists()){
                btnStateString = documentSnapshot.getString("gameOn");
                learningButton.setEnabled(Boolean.parseBoolean(btnStateString));
                videosButton.setEnabled(Boolean.parseBoolean(btnStateString));
                Log.d(TAG, "Current Data: " + documentSnapshot.getData());


            }else {
                Log.d(TAG,"Current Data: null" );
            }
        }
    });

But when I run the app it crashes after login when it tries to go to Home page and in the debug it gives me the reason is here:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.starkid, PID: 11907
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.starkid/com.example.starkid.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3341)

The error message:

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object reference

is telling you that mFirebaseAuth is null. That means you haven't assigned it a value yet (or ever). Before you run this code, you will need to give it a value with mFirebaseAuth = FirebaseAuth.getInstance(); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM