0

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");
        }


    }


}
9
  • 1
    If you encounter problems, it's best to create a MCVE when posting a question. You posted almost 400 (four hundred) lines of code for this issue. That's a lot for people to parse and try to debug online. Please edit your question and isolate the problem, in that way you increase your chances of being helped. Please take a moment and read how to ask a question. Commented Oct 28, 2022 at 11:50
  • 1
    Besides that, at which particular line of code are you getting that error? Commented Oct 28, 2022 at 11:50
  • Thanks for the suggestion @AlexMamo . I am getting error in firebasemethods class , incheckIfUsernameExists method. I already added a comment. Commented Oct 28, 2022 at 11:54
  • There is an NPE caused by .getUid() and using that in multiple parts of your code. Where exactly does the error occur? Commented Oct 28, 2022 at 12:16
  • 1
    Is that object is not null, then the NPE comes from another part of your code, right? Commented Oct 28, 2022 at 13:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

The user is authenticated. I am getting the user id . Logcat messages18:11:51.690 D setupFirebaseAuth: setting up firebase auth. 18:11:51.810 D checkCurrentUser: checking if user is logged in. 18:11:52.274 D checkCurrentUser: checking if user is logged in. 18:11:52.274 D onAuthStateChanged:signed_in:eB4DBIvWdsfXJ8aDFYdKWCGPYxU2
Try suggesting a way to Overcome this issue
How can the user be authenticated if you are trying to register them?
I just updated my answer.
Hey @Nithinreddy can you provide details on how this issue is going for you? If my answer helped you solve it, I would appreciate it if you marked it as correct!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.