Change Firebase Password | Android Studio | Java

How to change the password of an account on Firebase?

In this tutorial, we will programmatically update/change the password of an existing email/password account on Firebase using Android Studio IDE and Java language.
First of all, we will reauthenticate the user by authenticating the old/previous password, if that password is correct then input a new password to update.

>>Watch For Kotlin

Required Libraries:
dependencies {
    .
    . 
    .
    //firebase libs
    implementation 'com.google.firebase:firebase-auth:19.2.0'
    implementation 'com.google.firebase:firebase-core:17.2.3'
    .
    .
    .
}


activity_main.xml
<?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"
    android:background="#FAF9F9"
    android:gravity="center"
    android:padding="10dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/labelTv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="Update Password"
        android:textAlignment="center"
        android:textColor="#000"
        android:textSize="25sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/oldPassEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/labelTv"
        android:layout_marginTop="40dp"
        android:background="#fff"
        android:hint="Old Password"
        android:inputType="textPassword"
        android:padding="10dp" />

    <EditText
        android:id="@+id/newPassEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/oldPassEt"
        android:layout_marginTop="10dp"
        android:background="#fff"
        android:hint="New Password"
        android:inputType="textPassword"
        android:padding="10dp" />

    <Button
        android:id="@+id/updatePasswordBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/newPassEt"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:text="Update Password" />

</RelativeLayout>

MainActivity.java
package com.blogspot.atifsoftwares.myapplication;

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

import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.EmailAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {

    private FirebaseAuth firebaseAuth;

    private ProgressDialog pd;

    //UI widgets
    private EditText oldPassEt, newPassEt;
    private Button updatePasswordBtn;

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

        //init UI widgets
        oldPassEt = findViewById(R.id.oldPassEt);
        newPassEt = findViewById(R.id.newPassEt);
        updatePasswordBtn = findViewById(R.id.updatePasswordBtn);

        //init FirebaseAuth for use authentication
        firebaseAuth = FirebaseAuth.getInstance();

        //setup progress dialog
        pd = new ProgressDialog(this);
        pd.setMessage("Please Wait...");

        //handle click event to begin
        updatePasswordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //input data
                String oldPassword = oldPassEt.getText().toString().trim();
                String newPassword = newPassEt.getText().toString().trim();
                //validate data
                if (TextUtils.isEmpty(oldPassword)) {
                    Toast.makeText(getApplicationContext(), "Enter your current password...", Toast.LENGTH_SHORT).show();
                    return; //don't proceed further
                }
                if (newPassword.length() < 6) {
                    Toast.makeText(getApplicationContext(), "Password length must atleast 6 characters...", Toast.LENGTH_SHORT).show();
                    return;  //don't proceed further
                }
                updatePassword(oldPassword, newPassword);
            }
        });

    }

    private void updatePassword(String oldPassword, final String newPassword) {
        //show dialog
        pd.show();

        //get current user
        final FirebaseUser user = firebaseAuth.getCurrentUser();

        //before changing password re-authenticate the user
        AuthCredential authCredential = EmailAuthProvider.getCredential(user.getEmail(), oldPassword);
        user.reauthenticate(authCredential)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        //successfully authenticated, begin update

                        user.updatePassword(newPassword)
                                .addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        //password updated
                                        pd.dismiss();
                                        Toast.makeText(getApplicationContext(), "Password Updated...", Toast.LENGTH_SHORT).show();
                                    }
                                })
                                .addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        //failed updating password, show reason
                                        pd.dismiss();
                                        Toast.makeText(getApplicationContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                    }
                                });
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        //authentication failed, show reason
                        pd.dismiss();
                        Toast.makeText(getApplicationContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }
}

Output
Change Firebase Password | Android Studio | Kotlin

Comments

Popular posts from this blog

Manage External Storage Permission | Android Studio | Kotlin

Manage External Storage Permission | Android Studio | Java

Add a Back Button to Action Bar Android Studio (Kotlin)