Android: How to login an user with his phone number

Mayur Sadhu :

I'm creating an app with where I want already signed up users to be redirected to their profile if their phone number is registered in the app, but if he is a new user then he will be redirected to the welcome page. The problem is, I'm able to get the verification code for the phone number, but it is always redirecting to the welcome page irrespective of whether it is an existing user or a new user. By far I've implemented Firebase phone authentication, and

    private void verifyCode(String code) {

        PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(verificationId, code);
        signInWithCredentials(phoneAuthCredential);

    }

    private void signInWithCredentials(PhoneAuthCredential phoneAuthCredential) {

        mAuth.signInWithCredential(phoneAuthCredential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {


                final String num = getIntent().getStringExtra("phoneNumber");
                final Query query = FirebaseDatabase.getInstance().getReference("users").orderByChild("birthday").equalTo(num);

                if (task.isSuccessful()) {

                    if (num.equals(query.toString())) {

                        Log.i("Method", "Inside if block");
                        Log.i("value", num + query.toString());
                        Intent intent = new Intent(VerifyPhoneActivity.this, WelcomeActivity.class);

                        startActivity(intent);

                    } else {

                        Log.i("Method", "Inside if block2");
                        Log.i("value", num + query.toString());



                    Intent intent = new Intent(VerifyPhoneActivity.this, ProfileActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                    startActivity(intent);
                }


                } else {

                    Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();

                }
            }
        });

    }

I'm taking only the phone number of the user to log in/sign up, and there's no separate button for login and sign up. It should work in such a way that, once the OTP sent by the Firebase auth has been verified and if the phone number is already present in the database, it should directly fo the user's profile page instead of the welcome screen, however, if the phone number is new it should go to the welcome page instead of the user profile page. The challenge I'm facing is I'm not able to check if the number entered is already present in the database in the user table(I've created a separate user table to store the details of the user when he signs up for the first time).

MoTahir :

from what I understood you're able to register users but you're not able to redirect unregistered users to the login/signup screen, if that's the case then you can try to use

FirebaseAuth.getInstance().currentUser

in the on create view method in your welcome/home page it should be something like this

override fun onCreate(savedInstanceState: Bundle?) {

  if (FirebaseAuth.getInstance().currentUser == null) {
     startActivity(Intent(applicationContext, RegistrationActivity::class.java))
     finish()
     return
  } 

  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main)
  // do your other stuff

}

this code is written in kotlin it shouldn't be that different in java. hope it helps.

UPDATE------

you have a few mistakes with your code, try this

private void verifyCode(String code) {

    PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(verificationId, code);

    FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {

                final String num = getIntent().getStringExtra("phoneNumber");
                FirebaseDatabase.getInstance().getReference("users").orderByChild("phoneNumber").equalTo(num).addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if (dataSnapshot.exists()) {
                            Intent intent = new Intent(VerifyPhoneActivity.this, ProfileActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                        } else {
                            FirebaseDatabase.getInstance().getReference("users").push().child("phoneNumber").setValue(num).addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    Intent intent = new Intent(VerifyPhoneActivity.this, WelcomeActivity.class);

                                    startActivity(intent);

                                }
                            });
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
            } else {
                Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    });
}

first of all, you have to log in the user with the phone detail then you check if you have any user registered with that phone number if you do then that means that this user has already entered the app but if you didn't have any information of user with that phone number then you create his information and direct him to the welcome screen after creating his information, so if this user comes back again you will check if we have a record of user with that phone number (which we do) so this time he will be directed to the profile screen

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=358366&siteId=1