In any app, we got a feature to login using our email and password. Sometimes it happens that we want to change our email or we lost the password of our previous email so here we are going to implement the same feature to change our email using Firebase Authentication. Note that we are going to implement this project using the Java language.Â
Step by Step Implementation
Lets’ consider you have already an existing project or you may create a new project.Â
Step 1: Create a new Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Â
Step 2: Working with the XML file
Go to the XML file and refer to the following code. Below is the code for the XML file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:gravity="center"    tools:context=".ChangeEmail">       <EditText        android:id="@+id/email"        android:layout_width="267dp"        android:layout_height="wrap_content"        android:layout_alignParentStart="true"        android:layout_alignParentTop="true"        android:layout_marginStart="36dp"        android:layout_marginTop="120dp"        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="161dp"        android:ems="10"        android:hint="Password"        android:inputType="textPassword" />Â
    <EditText        android:id="@+id/change"        android:layout_width="259dp"        android:layout_height="58dp"        android:layout_alignParentStart="true"        android:layout_alignParentTop="true"        android:layout_marginStart="32dp"        android:layout_marginTop="211dp"        android:ems="10"        android:hint="Change Email"        android:inputType="textEmailAddress" />Â
    <Button        android:id="@+id/changeemail"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentStart="true"        android:layout_alignParentTop="true"        android:layout_marginStart="192dp"        android:layout_marginTop="277dp"        android:background="@color/colorPrimary"        android:text="Change Email Here"        android:textSize="15dp" />   </RelativeLayout> |
Â
Â
Step 3: Working with the Java file
Â
So the main part exists on the java file. In this file, we need to re-authenticate the user as according to the documentation changing the primary email address is a sensitive action. Below is the code snippet for doing the same.
Â
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();Â
// Get auth credentials from the user for re-authenticationAuthCredential credential = EmailAuthProvider.getCredential(email, password); // Current Login CredentialsÂ
// Prompt the user to re-provide their sign-in credentialsuser.reauthenticate(credential).addOnCompleteListener(new OnCompleteListener<Void>() {                    @Override                    public void onComplete(@NonNull Task<Void> task) {                                               Log.d("value", "User re-authenticated.");Â
                        // Now change your email address \\                        //----------------Code for Changing Email Address----------\\                        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();                        user.updateEmail(change.getText().toString()).addOnCompleteListener(new OnCompleteListener<Void>() {                                    @Override                                    public void onComplete(@NonNull Task<Void> task) {                                        if (task.isSuccessful()) {                                            Toast.makeText(ChangeEmail.this, "Email Changed" + " Current Email is " + change.getText().toString(), Toast.LENGTH_LONG).show();                                        }                             }                 });       }}); |
Â
Â
Below is the complete code for the Java file for the above XML file.
Â
Java
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.Button;import android.widget.EditText;import android.widget.Toast;Â
import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;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 ChangeEmail extends AppCompatActivity {Â
    FirebaseAuth auth;    Button changeemail;Â
    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_change_email);Â
        // Initialising the email and password        final EditText email = findViewById(R.id.email);        final EditText password = findViewById(R.id.logpass);        changeemail = findViewById(R.id.changeemail);Â
        // click on this to change email        changeemail.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                changeemail(email.getText().toString(), password.getText().toString());            }        });Â
    }Â
    EditText change;Â
    // Here we are going to change our email using firebase re-authentication    private void changeemail(String email, final String password) {Â
        change = findViewById(R.id.change);Â
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();Â
        // Get auth credentials from the user for re-authentication        AuthCredential credential = EmailAuthProvider.getCredential(email, password); // Current Login CredentialsÂ
        // Prompt the user to re-provide their sign-in credentials        user.reauthenticate(credential).addOnCompleteListener(new OnCompleteListener<Void>() {                    @Override                    public void onComplete(@NonNull Task<Void> task) {Â
                        Log.d("value", "User re-authenticated.");Â
                        // Now change your email address \\                        //----------------Code for Changing Email Address----------\\                        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();                        user.updateEmail(change.getText().toString()).addOnCompleteListener(new OnCompleteListener<Void>() {                                    @Override                                    public void onComplete(@NonNull Task<Void> task) {                                        if (task.isSuccessful()) {                                            Toast.makeText(ChangeEmail.this, "Email Changed" + " Current Email is " + change.getText().toString(), Toast.LENGTH_LONG).show();                                        }                                    }                                });                         }             });    }} |
Â
Â
Output:
Â
Â
