0

Problem I want my user details to be saved in the real time database (Firebase) by using setUpFirebaseAuth() method but i observed that the method is not entering into OnAuthStateChanged() part of the code

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

    private void ValidateDataandDoRegister() {
        String username=inputUsername.getText().toString().trim();
        String email=inputEmail.getText().toString().trim();
        String password=inputPassword.getText().toString().trim();
        String confirmPassword=inputConfirmPassword.getText().toString().trim();
        if(email.isEmpty()){
            inputEmail.setError("Enter Email Address");
            inputEmail.requestFocus();
            pb.setVisibility(View.GONE);
        }
        else if(email.length()<10){
            inputEmail.setError("Enter valid Email");
            inputEmail.requestFocus();
            pb.setVisibility(View.GONE);
        }
        else if(password.isEmpty()){
            inputPassword.setError("Enter the password");
            inputPassword.requestFocus();
            pb.setVisibility(View.GONE);
        }
        else if(password.length()<8){
            inputPassword.setError("Password should be greater than 8 characters");
            inputPassword.requestFocus();
            pb.setVisibility(View.GONE);
        }
        else if(confirmPassword.isEmpty()){
            inputConfirmPassword.setError("Re-Enter the Password");
            inputConfirmPassword.requestFocus();
            pb.setVisibility(View.GONE);
        }
        else if(confirmPassword.length()<8){
            inputConfirmPassword.setError("Password should be greater than 8 characters");
            inputConfirmPassword.requestFocus();
            pb.setVisibility(View.GONE);
        }
        else if(!password.equals(confirmPassword)){
            inputPassword.setError("Password not matched");
            inputPassword.requestFocus();
            inputConfirmPassword.setError("Password not matched");
            inputConfirmPassword.requestFocus();
            inputPassword.setText("");
            inputConfirmPassword.setText("");
            pb.setVisibility(View.GONE);
        }
        else{
            pb.setVisibility(View.VISIBLE);
            doRegister(username,email,password);
        }
    }

    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();
                }
                setupFirebaseAuth();
            }

        }).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();
            }
            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.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            //1st check: Make sure the username is not already in use
                            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
                            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();
    }

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

}

FirebaseMethods

```
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();
        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;
    }

    /**
     * Registering a new email and password
     * @param username
     * @param email
     * @param password
     */
    public void registerNewEmail(final String username,final String email,String password){
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(!task.isSuccessful()){
                            Toast.makeText(mContext, R.string.auth_failed, Toast.LENGTH_SHORT).show();
                        }
                        else if(task.isSuccessful()){
                            userID=mAuth.getCurrentUser().getUid();
                        }
                    }
                });
    }

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


    }


}

```

I tried directly calling my method firebaseMethods.addNewUser(email, username); but I am getting an error in addNewUser method as UserId is null. I am expecting to make sure that the User details gets added in database just after the user clicks the register button by making sure that the UserId is not null.

Tried

adding mAuth.addAuthStateListener(mAuthListener) method in onStart method

Error

Shows a null pointer exception in logcat, when i try to start the register activity

Logcat message

FATAL EXCEPTION: main
                                                                                                
Process: com.example.movies4u, PID: 6821
                                                                                                
java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.firebase.auth.FirebaseAuth$AuthStateListener.onAuthStateChanged(com.google.firebase.auth.FirebaseAuth)' on a null object reference
                                                                                                     
at com.google.firebase.auth.zzl.run(com.google.firebase:firebase-auth@@21.0.3:1)
                                                                                                     
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)
  • you never use `mAuthListener` in other context than `removeAuthStateListener` – Selvin Oct 26 '22 at 10:15
  • That wasn't clear. Can you add few more lines to that – Nithin reddy Oct 26 '22 at 10:19
  • You never set listener so how you expect to get it called – Selvin Oct 26 '22 at 11:01
  • I added mAuth.addAuthStateListener(mAuthListener) method in onStart method but because of that line the app is getting crashed as soon as I enter the register activity, so I removed it. Can you help me in spotting the error that is causing the app to crash. – Nithin reddy Oct 26 '22 at 11:32
  • When an app crashes, it writes an error message and stack trace to its logcat. Please find those, and add them to your question by clicking the `edit` link under it. Also see https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this and https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – Frank van Puffelen Oct 26 '22 at 14:21
  • Please edit your question and add the information Frank asked for, and please also respond using @. – Alex Mamo Oct 27 '22 at 10:06
  • @FrankvanPuffelen Added the logcat message – Nithin reddy Oct 27 '22 at 12:50

0 Answers0