Boris Ruzanov
Boris Ruzanov

Reputation: 105

ExceptionInInitializerError in Firebase

Because of using the same instances during the whole project I decided to put them in separate class and call them with static methods. The problem is that some of them works well some of them not. Don't understand what is the logic.

I got a class with instances (i know about dagger2 don't worry)

public class FirebaseReferences {

   public static FirebaseUser currentUserInstance = FirebaseAuth.getInstance().getCurrentUser();
   public static String currentUserUid = currentUserInstance.getUid();

   public static FirebaseUser getCurrentUserInstance(){
       return FirebaseAuth.getInstance().getCurrentUser();
   }

    public static DatabaseReference getCurrentUserUidReference(){
        return FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserUid);
    }

    static String getCurrentUserUidString(String uid){
        String currentUid = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserUid).toString();
        return currentUid;
    }

    public String getUserToken(){
        return FirebaseInstanceId.getInstance().getToken();
    }

}

And that the class where I am trying to call getCurrentUserInstance but hot error

firebaseAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                Log.v("RW", "onAuthStateChanged" );
                if (FirebaseReferences.getCurrentUserInstance() != null) {
                    Log.v("RW", "user is not null");
                    //Create new user
                    final String userName = FirebaseReferences.getCurrentUserInstance().getDisplayName();          
                    FirebaseReferences.getCurrentUserUidReference().addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {

                            //the image is still the default one
                            HashMap<String, String> userMap = new HashMap<>();
                            userMap.put("name", userName);
                            userMap.put("image", "default");
                            userMap.put("thumb_image", "default");
                            userMap.put("status", "Your status is here...");
                            FirebaseReferences.getCurrentUserUidReference().setValue(userMap);


                        }

The error code

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.borisruzanov.russianwives, PID: 19900
              java.lang.ExceptionInInitializerError
                  at com.borisruzanov.russianwives.utils.FirebaseReferences.getCurrentUserInstance(FirebaseReferences.java:14)
                  at com.borisruzanov.russianwives.utils.AuthStateListenerUtil$1.onAuthStateChanged(AuthStateListenerUtil.java:34)
                  at com.google.firebase.auth.zzi.run(Unknown Source)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
                  at com.borisruzanov.russianwives.utils.FirebaseReferences.<clinit>(FirebaseReferences.java:11)

I am not sure but maybe I make a mistake that I am trying to save that inctances in separate class? Or maybe there is better practice how I can do that? But anyway I don't want to copy paste all that instances which are similar in all classes

PS. I tried to edit code and it works now. But the strange thing is that here FirebaseUser user = firebaseAuth.getCurrentUser();I use FirebaseUser with a variable without calling static method and it works when I use static it doesn't work. But at the same time in the line FirebaseReferences.getCurrentUserUidReference(). it works with static

     public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                    FirebaseUser user = firebaseAuth.getCurrentUser();
                    Log.v("RW", "onAuthStateChanged" );
                    if (user != null) {
                        Log.v("RW", "user is not null");
                        //Create new user
                        String uid = user.getUid();
                        final String userName = FirebaseReferences.getCurrentUserInstance().getDisplayName();

                        FirebaseReferences.getCurrentUserUidReference().addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {

Upvotes: 1

Views: 1698

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 139019

When you want to use, for example the currentUserInstance just simply use it. There is no need to create a getCurrentUserInstance() method that returns the same thing. With other words, all those methods declarations can be removed and use only the static fields: currentUserInstance, currentUserUid and so on.

It doesn't work because you are creating a new instance of FirebaseAuth class every time by calling FirebaseAuth.getInstance() which is not correct. You only neet to create it once.

FirebaseUser firebaseUser = Firebase.getInstance().getCurrentUser();

And now use this firebaseUser object to get the uid or the tokenId or what you else need.

Upvotes: 0

Kushan
Kushan

Reputation: 5984

There is no valid Firebase user logged in via their auth triggers. This can happen if the session has expired, the user is no longer valid or disabled.

Always put a null check before using any user related data

if(Firebase.getInstance().getCurrentUser()!=null){
  //Do your thing
}

Basically, your static method getCurrentUserInstance() is returning a null user and you are calling getUserId() on this null reference. Put a null check on the result

Upvotes: 1

Related Questions