Nithin reddy
Nithin reddy

Reputation: 21

Getting a null pointer Exception as 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference

Problem

I am trying to make user credentials like username and email to get added in the realtime database. After the user enters their data and hits register button i am getting an error with firebaseMethods.checkIfUsernameExists() method.

Error

FATAL EXCEPTION: main
                 Process: com.example.movies4u, PID: 25475
                 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
                    at com.example.movies4u.Utils.FirebaseMethods.checkIfUsernameExists(FirebaseMethods.java:47)
                    at com.example.movies4u.activity_register$1$1.onDataChange(activity_register.java:200)
                    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
                    at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
                    at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
                    at android.os.Handler.handleCallback(Handler.java:873)
                    at android.os.Handler.dispatchMessage(Handler.java:99)
                    at android.os.Looper.loop(Looper.java:224)
                    at android.app.ActivityThread.main(ActivityThread.java:7081)
                    at java.lang.reflect.Method.invoke(Native Method)
                    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604)
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)

Register Activity Code

package com.example.movies4u;

import static android.content.ContentValues.TAG;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.movies4u.Utils.FirebaseMethods;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class activity_register extends AppCompatActivity {
    TextView HaveAccount;
    EditText inputUsername,inputEmail,inputPassword,inputConfirmPassword;
    String username,email,password;
    Button btnRegister;
    FirebaseAuth mAuth;
    ProgressBar pb;
    private String userID;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private FirebaseMethods firebaseMethods;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;

    private String append;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); //Hide status Bar
        setContentView(R.layout.activity_register);
        firebaseMethods =new FirebaseMethods(activity_register.this);

        HaveAccount= (TextView) findViewById(R.id.HaveAccount);
        pb = findViewById(R.id.progressBar3);
        inputUsername=findViewById(R.id.inputUsername);
        inputEmail=findViewById(R.id.inputEmail);
        inputPassword=findViewById(R.id.inputPassword);
        inputConfirmPassword=findViewById(R.id.inputConfirmPassword);
        btnRegister=findViewById(R.id.btnRegister);
        username=inputUsername.getText().toString();
        email=inputEmail.getText().toString();
        password=inputPassword.getText().toString();

        pb.setVisibility(View.GONE);
        HaveAccount.setOnClickListener(view -> {
            Intent loginintent=new Intent(activity_register.this,login_activity.class);
            startActivity(loginintent);
        });

        mAuth=FirebaseAuth.getInstance();
        btnRegister.setOnClickListener(view -> ValidateDataandDoRegister());
    }

// we will call the method doRegister(username,email,password); in validateDataandDoRegister()

    private void doRegister(String username,String email, String password) {
        pb.setVisibility(View.VISIBLE);
        mAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(task -> {
            if(task != null ){
                if(mAuth.getCurrentUser() != null){
                    userID=mAuth.getCurrentUser().getUid();
                }

//                firebaseMethods.registerNewEmail(username,email,password);
                sendVerificationEmail();
//                firebaseMethods.addNewUser(email, username);
            }

        }).addOnFailureListener(e -> {
            if(e instanceof FirebaseAuthUserCollisionException){
                btnRegister.setEnabled(true);
                inputEmail.setError("Email Already Registered");
                pb.setVisibility(View.GONE);
                inputEmail.requestFocus();
            }
            else{
                btnRegister.setEnabled(true);
                pb.setVisibility(View.GONE);
                Toast.makeText(activity_register.this, "Oops! Something Went wrong", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void sendVerificationEmail() {
        mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(task -> {
            if(task != null && task.isSuccessful()){
                btnRegister.setEnabled(true);
                pb.setVisibility(View.GONE);
                Toast.makeText(activity_register.this, "Email has been sent to your email address", Toast.LENGTH_SHORT).show();
                //fixing the bug
                mAuth.signOut();
            }
            else {
                btnRegister.setEnabled(true);
                pb.setVisibility(View.GONE);
                Toast.makeText(getApplicationContext(), "Oops! failed to send verification email",Toast.LENGTH_SHORT).show();
            }
        });
    }


    /*
    ------------------------------------ Firebase ---------------------------------------------
     */

    /**
     * Setup the firebase auth object
     */
    private void setupFirebaseAuth(){
        Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
        mAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference();

        //cannot get into this part of code
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user=firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());

                    myRef.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            //1st check: Make sure the username is not already in use

                            //Error Occured in the below checkifUsernameExists method call  
                            if(firebaseMethods.checkIfUsernameExists(username, dataSnapshot)){
                                //to randomly generate key to make sure username is unique
                                append = myRef.push().getKey().substring(3,10);
                                Log.d(TAG, "onDataChange: username already exists. Appending random string to name: " + append);
                            }
                            username = username + append;

                            //add new user to the database
                            Log.d(TAG, "adding new user to database");
                            firebaseMethods.addNewUser(email, username);
                            Toast.makeText(activity_register.this, "SignUp successful", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            Toast.makeText(activity_register.this, "unsuccessful", Toast.LENGTH_SHORT).show();
                        }
                    });
                    finish();

                } else {
                    // User is signed out
                    Toast.makeText(activity_register.this, "unsuccessful", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onAuthStateChanged:signed _out");
                }
                // ...
            }
        };
    }

    @Override
    public void onStart() {
        super.onStart();
        setupFirebaseAuth();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

}

FirebaseMethods Code

package com.example.movies4u.Utils;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.movies4u.Models.User;
import com.example.movies4u.Models.UserAccountSettings;
import com.example.movies4u.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class FirebaseMethods {
    private static final String TAG="FirebaseMethods";

    //Firebase
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
    private String userID;

    private Context mContext;

    public FirebaseMethods(Context context){
        mAuth=FirebaseAuth.getInstance();
        mFirebaseDatabase =FirebaseDatabase.getInstance();
        myRef=mFirebaseDatabase.getReference();
        mContext =context;

        if(mAuth.getCurrentUser() !=null){
            userID =mAuth.getCurrentUser().getUid();
        }
    }

    public boolean checkIfUsernameExists(String username, DataSnapshot dataSnapshot){
        User user =new User();
        //Getting error in the below line
        for (DataSnapshot ds: dataSnapshot.child(userID).getChildren()){
            user.setUsername(ds.getValue(User.class).getUsername());

            if(StringManipulation.expandUsername(user.getUsername()).equals(username)){
                return true;
            }
        }
        return false;
    }

   

    public void addNewUser(String email, String username){
        User user=new User(email,username);
        if(userID!=null)
        {
            myRef.child(mContext.getString(R.string.dbname_users))
                    .child(userID)
                    .setValue(user).addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void unused) {
                            Log.d(TAG, "user added");
                            Toast.makeText(mContext, "user added", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.d(TAG, "user not added");
                            Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });

            UserAccountSettings settings = new UserAccountSettings(username, username);

            myRef.child(mContext.getString(R.string.dbname_user_account_settings))
                    .child(userID)
                    .setValue(settings);
        }
        else {
            Log.d(TAG, "user is null");
        }


    }


}

Upvotes: 0

Views: 501

Answers (1)

mrkachariker
mrkachariker

Reputation: 421

You are initializing the userID variable like this:

if(mAuth.getCurrentUser() != null){
    userID =mAuth.getCurrentUser().getUid();
}

When registering, the user is not authenticated yet. Therefore, userID is null. You could check this with the debugger.

In the register method there should not be a method to call for currently authenticated user, since you are trying to register a new user and they are not able to login/authenticate just yet.

Instead, try passing the userDTO object you get from the data the future/potential user inputed and check for validity of username (and other invariants you might have) before allowing the registration.

Upvotes: 1

Related Questions