Authenticate with Firebase on Android using a Phone Number with Custom User Fields.

ronnystudio-Authenticate with Firebase on Android using a Phone Number with Custom User Fields
Login with Mobile is very important when we create a real time application so here is the , Authenticate with Firebase on Android using a Phone Number with Custom User Fields.

Here is a solution for phone authenticate firebase how to add custom user fields while using mobile phone number authentication.

Before you begin

Connect Your Android Studio project with a firebase.

Open android studio clicks on Tools and hit on the firebase tab. refer to the below image.

After click on firebase choose the firebase auth option and follow the steps.

If you still have some questions you can follow this URL as well as Firebase to your Android project.

Enable Firebase Phone Authentication

To do this go to Firebase Console and open the project that you are using.

Then go to Sign In Method and enable Phone Authentication.

Step 01 :

Create a new project in Android Studio from the File ⇒ New Project. As it prompts you to select the default activity, select Empty Activity and proceed.

Name your project as per your convenience and click finish.

Download this res.zip and add them to your project res folder. This file contains a few drawable images and font folder required for this app.

Now that we are done with the images, moving on to changing the text font. For this, we would need to add a custom font in our directory and asset folder as well. find custom fonts folder and asset folder and paste it under the java. Here is a reference image for custom fonts folder

Watch this video tutorial for step 1 here.

Step 02 :

Open colors.xml located under res ⇒ values and add the below color values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#435bd4</color>
    <color name="colorPrimaryDark">#435bd4</color>
    <color name="colorAccent">#D81B60</color>
    <color name="white">#ffffff</color>
    <color name="grey_60">#666666</color>
    <color name="textColor">#070707</color>
    <color name="appcolor">#435bd4</color>

</resources>

Open strings.xml located under res ⇒ values and add the below values.

<resources>
    <string name="app_name">HDFCReferApp</string>


    <string name="appbar_scrolling_view_behavior">android.support.design.widget.AppBarLayout$ScrollingViewBehavior</string>
    <string name="bottom_sheet_behavior">android.support.design.widget.BottomSheetBehavior</string>
    <string name="password_toggle_content_description">Show password</string>
    <string name="search_menu_title">Search</string>
    <string name="status_bar_notification_info_overflow">999+</string>
    <string name="next">NEXT</string>
    <string name="mobile_number">mobile number</string>
    <string name="enter_mobile_number">Enter Mobile Number</string>
    <string name="mobile_login_example">Mobile Login example</string>
    <string name="otp_verification">OTP Verification</string>
    <string name="x_x_x_x_x_x">X X X X X X</string>
</resources>

Open styles.xml located under res ⇒ values and add the below values.

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowFullscreen">true</item>
    </style>

</resources>

Step 03 :

Now is the time for making the XML file. For this, Open activity_main.xml and paste the following code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="21dp"
            android:fontFamily="@font/sfpro_display_medium"
            android:layout_marginLeft="21dp"
            android:layout_marginTop="21dp"
            android:layout_marginBottom="14dp"
            android:text="@string/mobile_login_example"
            android:textColor="@color/textColor"
            android:textSize="13sp" />

        <View
            android:layout_width="match_parent"
            android:layout_height="0.7dp"
            android:background="#dddddd" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="24dp"
            android:layout_marginLeft="24dp"
            android:layout_marginTop="25dp"
            android:text="@string/enter_mobile_number"
            android:fontFamily="@font/sfpro_display_medium"
            android:textColor="@color/textColor"
            android:textSize="23sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="48dp"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/editTextMobile"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="34dp"
                android:layout_marginLeft="34dp"
                android:layout_weight="1"
                android:background="#00000000"
                android:fontFamily="@font/sfpro_display_regular"
                android:hint="@string/mobile_number"
                android:inputType="phone"
                android:textColor="@color/textColor"
                android:textColorHint="@color/grey_60"
                android:textSize="13sp" />

            <ImageView
                android:layout_width="15dp"
                android:layout_height="20dp"
                android:layout_marginEnd="50dp"
                android:tint="@color/appcolor"
                android:layout_marginRight="50dp"
                android:src="@drawable/ic_phone_android_black_24dp" />
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginStart="28dp"
            android:layout_marginLeft="28dp"
            android:layout_marginTop="10dp"
            android:layout_marginEnd="44dp"
            android:layout_marginRight="44dp"
            android:background="#9f9e9e" />



    </LinearLayout>


    <TextView
        android:id="@+id/tv_mobile_continue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="27dp"
        android:layout_marginRight="27dp"
        android:layout_marginBottom="16dp"
        android:background="@color/appcolor"
        android:elevation="1dp"
        android:gravity="center_horizontal"
        android:paddingTop="18.5dp"
        android:paddingBottom="18.5dp"
        android:text="@string/next"
        android:textAllCaps="false"
        android:textColor="#ffffff"
        android:textSize="12sp" />


</RelativeLayout>

Step 04 :

Now open MainActivity java file and write the following code.

package com.example.mobileloginwithcustom;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {

    private TextView tv_mobile_continue;
    private EditText editTextMobile;
    private FirebaseAuth auth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        auth = FirebaseAuth.getInstance();

        if (auth.getCurrentUser() != null) {
            startActivity(new Intent(MainActivity.this, MasterActivity.class));
            finish();
        }

        editTextMobile = findViewById(R.id.editTextMobile);

        tv_mobile_continue = findViewById(R.id.tv_mobile_continue);
        tv_mobile_continue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String mobile = editTextMobile.getText().toString().trim();

                if(mobile.isEmpty() || mobile.length() < 10){
                    editTextMobile.setError("Enter a valid mobile");
                    editTextMobile.requestFocus();
                    return;
                }

                Intent intent = new Intent(MainActivity.this, MobileVerification.class);
                intent.putExtra("mobile", mobile);
                startActivity(intent);

            }
        });


    }
}

Step 05 :

Now this time we required one more activity for mobile OTP verification so for this create New Emplty Activity and name it MobileVerification and open its XML file. activity_mobile_verification and paste the following code.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MobileVerification"
    android:background="#ffffff">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#ffffff">
        <customfonts.MyTextView_Roboto_Medium
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="13sp"
            android:textColor="@color/textColor"
            android:text="@string/mobile_login_example"
            android:layout_marginTop="21dp"
            android:layout_marginLeft="21dp"
            android:layout_marginBottom="14dp"
            android:layout_marginStart="21dp" />
        <View
            android:layout_width="match_parent"
            android:layout_height="0.7dp"
            android:background="#dddddd"/>
        <customfonts.MyTextView_Roboto_Black
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/otp_verification"
            android:layout_marginLeft="24dp"
            android:layout_marginTop="25dp"
            android:textColor="@color/textColor"
            android:textSize="23sp"
            android:layout_marginStart="24dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="horizontal"
            android:layout_marginTop="48dp"
            android:layout_height="wrap_content">


            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="13sp"
                android:id="@+id/editTextCode"
                android:background="#00000000"
                android:layout_marginRight="34dp"
                android:layout_marginEnd="34dp"
                android:hint="@string/x_x_x_x_x_x"
                android:fontFamily="@font/sfpro_display_medium"
                android:textColor="@color/grey_60"
                android:layout_marginTop="48dp"
                android:layout_marginLeft="34dp"
                android:layout_marginStart="34dp" />



        </LinearLayout>



        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#9f9e9e"
            android:layout_marginLeft="28dp"
            android:layout_marginRight="44dp"
            android:layout_marginTop="12dp"
            android:layout_marginStart="28dp"
            android:layout_marginEnd="44dp" />


    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/next"
        android:textSize="12sp"
        android:id="@+id/tv_otpcode"
        android:gravity="center_horizontal"
        android:textColor="#ffffff"
        android:background="@color/appcolor"
        android:paddingTop="18.5dp"
        android:paddingBottom="18.5dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="27dp"
        android:layout_marginRight="27dp"
        android:textAllCaps="false"
        android:elevation="1dp" />




</RelativeLayout>

Step 06 :

Now open MobileVerification java file and write the following code.

package com.example.mobileloginwithcustom;

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

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskExecutors;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
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;

import java.util.concurrent.TimeUnit;

public class MobileVerification extends AppCompatActivity {

    private TextView tv_otpcode;
    private String mVerificationId;
    private EditText editTextCode;
    private FirebaseAuth mAuth;
    private FirebaseDatabase firebaseDatabase;
    private DatabaseReference databaseReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mobile_verification);


        mAuth = FirebaseAuth.getInstance();
        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("appusers");


        editTextCode = findViewById(R.id.editTextCode);


        Intent intent = getIntent();
        final String mobile = intent.getStringExtra("mobile");

        //check if mobile number is already in DB or not with following code.

        /*databaseReference.orderByChild("usermobilenumber").equalTo(mobile).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                Toast.makeText(MobileVerification.this, "Mobile Number wih this user is already Exist", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                sendVerificationCode(mobile);

            }
        });*/

        sendVerificationCode(mobile);




        tv_otpcode = findViewById(R.id.tv_otpcode);
        tv_otpcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String code = editTextCode.getText().toString().trim();
                if (code.isEmpty() || code.length() < 6) {
                    editTextCode.setError("Enter valid code");
                    editTextCode.requestFocus();
                    return;
                }


                verifyVerificationCode(code);
            }
        });
    }

    private void sendVerificationCode(String mobile) {
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                "+91" + mobile,
                60,
                TimeUnit.SECONDS,
                TaskExecutors.MAIN_THREAD,
                mCallbacks);
    }


    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {


            String code = phoneAuthCredential.getSmsCode();


            if (code != null) {
                editTextCode.setText(code);

                verifyVerificationCode(code);
            }
        }

        @Override
        public void onVerificationFailed(FirebaseException e) {
            Toast.makeText(MobileVerification.this, e.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            super.onCodeSent(s, forceResendingToken);


            mVerificationId = s;
        }
    };


    private void verifyVerificationCode(String code) {

        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, code);


        signInWithPhoneAuthCredential(credential);
    }

    private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(MobileVerification.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            //verification successful we will start the profile activity
                            Intent intent = new Intent(MobileVerification.this, YourContactDetails.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);

                        } else {


                            String message = "Somthing is wrong, we will fix it soon...";

                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                message = "Invalid code entered...";
                            }

                            Snackbar snackbar = Snackbar.make(findViewById(R.id.parent), message, Snackbar.LENGTH_LONG);
                            snackbar.setAction("Dismiss", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                            snackbar.show();
                        }
                    }
                });
    }
}

Step 07 :

Now here is the Main part which we are focusing on. to add a custom field we required a firebase real-time database. so stay tuned for a while and follow the step by step process.

create a new Activity with the name of YourContactDetails.

open the layout file of this activity which is activity_your_contact_details.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:aapt="http://schemas.android.com/aapt"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical">

    <ProgressBar
        android:layout_width="wrap_content"
        android:visibility="gone"
        android:id="@+id/progressbar"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="256dp"/>

    <ScrollView
        android:layout_width="match_parent"
        android:scrollbars="none"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingBottom="150dp">





            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="23dp"
                android:layout_marginRight="23.2dp"
                android:orientation="vertical">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="40dp"
                    android:src="@drawable/back" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="17.7dp"
                    android:fontFamily="@font/sfpro_display_semibold"
                    android:letterSpacing="0.0325"
                    android:text="First, give us a few basic details about yourself"
                    android:textColor="#464646"
                    android:textSize="20sp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="35dp"
                    android:fontFamily="@font/sfpro_display_medium"
                    android:letterSpacing="0.0325"
                    android:text="Name"
                    android:textColor="#464646"
                    android:textSize="16.7sp" />

                <EditText
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/user_name"
                    android:layout_marginBottom="13.5dp"
                    android:background="@android:color/transparent"
                    android:layout_marginTop="7dp"
                    android:fontFamily="@font/sfpro_display_regular"
                    android:letterSpacing="0.0325"
                    android:hint="Rohan Surve"
                    android:textColor="#464646"
                    android:textSize="14.3sp" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="0.7dp"
                    android:background="#b6b6b6" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="15.5dp"
                    android:fontFamily="@font/sfpro_display_medium"
                    android:letterSpacing="0.0325"
                    android:text="Mobile Number"
                    android:textColor="#464646"
                    android:textSize="16.7sp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="13.5dp"
                    android:layout_marginTop="7dp"
                    android:id="@+id/user_mobile"
                    android:fontFamily="@font/sfpro_display_regular"
                    android:letterSpacing="0.0325"
                    android:hint="9821052454"
                    android:background="@android:color/transparent"
                    android:textColor="#464646"
                    android:textSize="12.3sp" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="0.7dp"
                    android:background="#b6b6b6" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="15.5dp"
                    android:fontFamily="@font/sfpro_display_medium"
                    android:letterSpacing="0.0325"
                    android:text="Email"
                    android:textColor="#464646"
                    android:textSize="16.7sp" />

                <EditText
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="13.5dp"
                    android:layout_marginTop="7dp"
                    android:id="@+id/user_email"
                    android:background="@android:color/transparent"
                    android:fontFamily="@font/sfpro_display_regular"
                    android:letterSpacing="0.0325"
                    android:hint="rohan.surve5@gmail.com"
                    android:textColor="#464646"
                    android:textSize="12.3sp" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="0.7dp"
                    android:background="#b6b6b6" />

                <TextView
                    android:textSize="15sp"
                    android:textColor="@color/white"
                    android:id="@+id/tv_updateuserdetail"
                    android:background="@drawable/rectangle_cure_blue"
                    android:paddingTop="16.3dp"
                    android:paddingBottom="16.3dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"

                    android:layout_marginTop="45dp"

                    android:text="Submit"
                    android:fontFamily="@font/sfpro_display_medium"
                    android:textAlignment="center"/>


            </LinearLayout>

        </LinearLayout>
    </ScrollView>

</RelativeLayout>

Step 08 :

Now open the YourContactDetails .java file and write the following code.

package com.example.mobileloginwithcustom;

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

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mobileloginwithcustom.model.AppUser;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.FirebaseDatabase;

public class YourContactDetails extends AppCompatActivity {

    private EditText user_name, user_email;
    private TextView user_mobile, tv_updateuserdetail;
    ProgressBar progressbar;
    FirebaseAuth firebaseAuth;
    private FirebaseAuth.AuthStateListener authListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_your_contact_details);


        firebaseAuth = FirebaseAuth.getInstance();

        user_name = findViewById(R.id.user_name);
        user_mobile = findViewById(R.id.user_mobile);
        user_email = findViewById(R.id.user_email);
        progressbar = findViewById(R.id.progressbar);
        tv_updateuserdetail = findViewById(R.id.tv_updateuserdetail);

        tv_updateuserdetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = user_name.getText().toString().trim();
                String useremail = user_email.getText().toString().trim();
                String usermobilenumber = user_mobile.getText().toString().trim();

                //checking if email and passwords are empty
                if (TextUtils.isEmpty(username)) {
                    Toast.makeText(YourContactDetails.this, "Please enter name", Toast.LENGTH_LONG).show();
                    return;
                }

                if (TextUtils.isEmpty(useremail)) {
                    Toast.makeText(YourContactDetails.this, "Please enter password", Toast.LENGTH_LONG).show();
                    return;
                }

                //if the email and password are not empty
                //displaying a progress dialog

                progressbar.setVisibility(View.VISIBLE);

                AppUser appUser = new AppUser(username, useremail, usermobilenumber);

                FirebaseDatabase.getInstance()
                        .getReference("appusers")
                        .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                        .setValue(appUser)
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {

                                if (task.isSuccessful()) {
                                    progressbar.setVisibility(View.GONE);
                                    Toast.makeText(YourContactDetails.this, "Registration Successful", Toast.LENGTH_SHORT).show();
                                    startActivity(new Intent(YourContactDetails.this, MasterActivity.class));
                                    finish();
                                } else {
                                    progressbar.setVisibility(View.GONE);
                                    Toast.makeText(YourContactDetails.this, "Registration failed , Something went wrong ", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            }
        });


    }

    @Override
    public void onStart() {
        super.onStart();
        FirebaseUser currentUser = firebaseAuth.getCurrentUser();
        if (currentUser == null) {
            // No user is signed in
        } else {
            user_mobile.setText(currentUser.getPhoneNumber());
        }
    }
}

Step 09 :

Time to Design MasterActivity to redirect when OTP is verified and data is successfully added to the firebase realtime database. in this activity, I am also doing the SignOut method.

So create one MasterActivity.java file and open its XML layout and write the following code.

activity_master.XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".MasterActivity">

    <LinearLayout
        android:orientation="vertical"
        android:paddingBottom="29.8dp"
        android:layout_width="match_parent"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_marginTop="23dp">
        <TextView
            android:textSize="17.3sp"
            android:textColor="#1d1d1d"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="23.3dp"
            android:text="Need Help?"
            android:fontFamily="@font/sfpro_display_semibold"
            android:letterSpacing="0.0325"/>
        <TextView
            android:textSize="12sp"
            android:textColor="#1d1d1d"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="11.7dp"
            android:text="have queries regarding this tutorial?\ngo to website and do comment."
            android:lineSpacingExtra="3dp"
            android:fontFamily="@font/sfpro_display_medium"
            android:textAlignment="center"
            android:letterSpacing="0.0425"/>
        <LinearLayout
            android:layout_gravity="center"
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp">
            <LinearLayout
                android:orientation="vertical"

                android:background="@drawable/rectangle_cure_gray"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                <TextView
                    android:textSize="14.7sp"
                    android:textColor="#91959d"

                    android:paddingLeft="20dp"
                    android:paddingTop="2.5dp"
                    android:paddingRight="20dp"
                    android:paddingBottom="2.5dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="www.ronnystudio.com"
                    android:fontFamily="@font/sfpro_display_medium"/>
            </LinearLayout>
            <LinearLayout
                android:orientation="vertical"
                android:id="@+id/lay_signout"
                android:background="@drawable/rectangle_cure_gray"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="8dp">
                <TextView
                    android:textSize="14.7sp"
                    android:textColor="#91959d"
                    android:paddingLeft="20dp"
                    android:paddingTop="2.5dp"
                    android:paddingRight="20dp"
                    android:paddingBottom="2.5dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Sign Out"
                    android:fontFamily="@font/sfpro_display_medium"/>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

Step 10 :

Write the MasterActivity code.

package com.example.mobileloginwithcustom;

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

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import static android.content.ContentValues.TAG;

public class MasterActivity extends AppCompatActivity {

    private LinearLayout lay_signout;
    private FirebaseAuth firebaseAuth;
    private FirebaseDatabase firebaseDatabase;
    private DatabaseReference databaseReference;
    private String userID;
    private FirebaseAuth.AuthStateListener mAuthListener;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_master);

        lay_signout = findViewById(R.id.lay_signout);
        lay_signout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signOut();
            }
        });

        //get firebase auth instance
        firebaseAuth = FirebaseAuth.getInstance();



        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {

                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());

                } else {
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                    Intent intent = new Intent(MasterActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                   finish();
                }
                // ...
            }
        };
    }

    private void signOut() {
        firebaseAuth.signOut();
    }


    @Override
    public void onStart() {
        super.onStart();
        FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
    }

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

Now run the app and see the output, you will see the output.

So that’s all for this Authenticate with Firebase on Android using a Phone Number with Custom User Fields. Tutorial. If you are having any confusion or queries please do comment. Thank You.

Facebook
Twitter
LinkedIn
Reddit
StumbleUpon
Pinterest
WhatsApp

Leave a comment

Your email address will not be published. Required fields are marked *

Related Posts