In many apps, we got a feature to login using our email and password. Sometimes it happens that we forget the password and most of the time there reset our password. Here we are going to implement the same feature to Reset our password using Firebase Authentication. You may refer to the following article User authentication using Firebase in Android. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.Â
Step by Step Implementation
Step 1: Working with the UI part
Go to the activity_login.xml file and refer to the following code. Below is the code for the activity_login.xml file.
XML
| <?xmlversion="1.0"encoding="utf-8"?><RelativeLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".LoginActivity">      <include        android:id="@+id/login_toolbar"        layout="@layout/app_bar_layout"/>      <TextView        android:id="@+id/textView2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentStart="true"        android:layout_alignParentTop="true"        android:layout_marginStart="19dp"        android:layout_marginTop="96dp"        android:textSize="25dp"        android:text="Login to Your Account"/>      <EditText        android:id="@+id/logemail"        android:layout_width="267dp"        android:layout_height="wrap_content"        android:layout_alignParentStart="true"        android:layout_alignParentTop="true"        android:layout_marginStart="36dp"        android:layout_marginTop="198dp"        android:ems="10"        android:hint="Email"        android:inputType="textEmailAddress"/>      <EditText        android:id="@+id/logpass"        android:layout_width="259dp"        android:layout_height="58dp"        android:layout_alignParentStart="true"        android:layout_alignParentTop="true"        android:layout_marginStart="32dp"        android:layout_marginTop="261dp"        android:ems="10"        android:hint="Password"        android:inputType="textPassword"/>      <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/forgetpass"        android:layout_alignParentStart="true"        android:layout_alignParentTop="true"        android:layout_marginStart="132dp"        android:layout_marginTop="351dp"        android:text="Forget Password"/>    <Button        android:id="@+id/logbut"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentStart="true"        android:layout_alignParentTop="true"        android:layout_marginStart="222dp"        android:layout_marginTop="387dp"        android:background="@color/colorPrimary"        android:text="Login"        android:textSize="15dp"/>  </RelativeLayout> | 
Step 2: Working with the LoginActivity.java file
Go to the LoginActivity.java file and refer to the following code. Below is the code for the LoginActivity.java fileÂ
Java
| importandroidx.annotation.NonNull;importandroidx.appcompat.app.AppCompatActivity;importandroidx.appcompat.widget.Toolbar;  importandroid.app.AlertDialog;importandroid.app.ProgressDialog;importandroid.content.DialogInterface;importandroid.content.Intent;importandroid.os.Bundle;importandroid.text.InputType;importandroid.text.TextUtils;importandroid.view.View;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.LinearLayout;importandroid.widget.TextView;importandroid.widget.Toast;  importcom.google.android.gms.tasks.OnCompleteListener;importcom.google.android.gms.tasks.OnFailureListener;importcom.google.android.gms.tasks.Task;importcom.google.firebase.auth.AuthResult;importcom.google.firebase.auth.FirebaseAuth;  publicclassLoginActivity extendsAppCompatActivity {      privateEditText memail;    privateEditText mpass;    privateFirebaseAuth mAuth;    privateToolbar mtoolbar;    privateButton login;    TextView forgetpass;    publicProgressDialog loginprogress;  Â    @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_login);      Â        mtoolbar=(Toolbar)findViewById(R.id.login_toolbar);        setSupportActionBar(mtoolbar);      Â        mAuth = FirebaseAuth.getInstance();        getSupportActionBar().setTitle("Login");      Â        forgetpass=findViewById(R.id.forgetpass);        getSupportActionBar().setDisplayHomeAsUpEnabled(true);        loginprogress=newProgressDialog(this);        memail=(EditText)findViewById(R.id.logemail);        mpass=(EditText)findViewById(R.id.logpass);      Â        // click on forget password text        forgetpass.setOnClickListener(newView.OnClickListener() {            @Override            publicvoidonClick(View v) {                showRecoverPasswordDialog();            }        });      Â        login=(Button)findViewById(R.id.logbut);        login.setOnClickListener(newView.OnClickListener() {            @Override            publicvoidonClick(View v) {                String email=memail.getText().toString();                String password =mpass.getText().toString();                if(!TextUtils.isEmpty(email)||!TextUtils.isEmpty(password)){                    loginprogress.setTitle("Logging In");                    loginprogress.setMessage("Please Wait ");                    loginprogress.setCanceledOnTouchOutside(false);                    loginprogress.show();                    loginUser(email,password);                }            }        });    }  Â    ProgressDialog loadingBar;  Â    privatevoidshowRecoverPasswordDialog() {        AlertDialog.Builder builder=newAlertDialog.Builder(this);        builder.setTitle("Recover Password");        LinearLayout linearLayout=newLinearLayout(this);        finalEditText emailet= newEditText(this);        Â        // write the email using which you registered        emailet.setText("Email");        emailet.setMinEms(16);        emailet.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);        linearLayout.addView(emailet);        linearLayout.setPadding(10,10,10,10);        builder.setView(linearLayout);        Â        // Click on Recover and a email will be sent to your registered email id        builder.setPositiveButton("Recover", newDialogInterface.OnClickListener() {            @Override            publicvoidonClick(DialogInterface dialog, intwhich) {                String email=emailet.getText().toString().trim();                beginRecovery(email);            }        });      Â        builder.setNegativeButton("Cancel", newDialogInterface.OnClickListener() {            @Override            publicvoidonClick(DialogInterface dialog, intwhich) {                dialog.dismiss();            }        });        builder.create().show();    }  Â    privatevoidbeginRecovery(String email) {        loadingBar=newProgressDialog(this);        loadingBar.setMessage("Sending Email....");        loadingBar.setCanceledOnTouchOutside(false);        loadingBar.show();        Â        // calling sendPasswordResetEmail        // open your email and write the new        // password and then you can login        mAuth.sendPasswordResetEmail(email).addOnCompleteListener(newOnCompleteListener<Void>() {            @Override            publicvoidonComplete(@NonNullTask<Void> task) {                loadingBar.dismiss();                if(task.isSuccessful())                {                    // if isSuccessful then done message will be shown                    // and you can change the password                    Toast.makeText(LoginActivity.this,"Done sent",Toast.LENGTH_LONG).show();                }                else{                    Toast.makeText(LoginActivity.this,"Error Occurred",Toast.LENGTH_LONG).show();                }            }        }).addOnFailureListener(newOnFailureListener() {            @Override            publicvoidonFailure(@NonNullException e) {                loadingBar.dismiss();                Toast.makeText(LoginActivity.this,"Error Failed",Toast.LENGTH_LONG).show();            }        });    }    publicvoidloginUser(String email,String password){        mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(newOnCompleteListener<AuthResult>() {            @Override            publicvoidonComplete(@NonNullTask<AuthResult> task) {                if(task.isSuccessful()){                    loginprogress.dismiss();                    Intent mainIntent = newIntent(LoginActivity.this,MainActivity.class);                    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);                    startActivity(mainIntent);                    finish();                } else{                    loginprogress.hide();                    Toast.makeText(LoginActivity.this,"Cannot Sign In..Please Try Again",Toast.LENGTH_LONG);                }            }        });    }} | 
Output:
GitHub link: https://github.com/Anni1123/LoginDemo

 
                                    







