Firebase Authentication - 10 - Delete account

Index

  1. Firebase setup
  2. Layout
  3. Register and Login
  4. Reset password
  5. Verify email
  6. Change profile picture
  7. Change display name
  8. Change email
  9. Change password
  10. Delete account

 

Welcome to the tenth and last part of the Firebase Authentication series! In the previous part I showed you how to change a users password in Android Studio with Firebase Authentication. In this part I will show you how to delete an account. It's going to be the same procedure as we are now familiar with. A user clicks on the Delete account option in the toolbar, a dialog is shown where the user confirm that he want to delete the account, and the account gets deleted.

Let us begin by creating a new xml file in res/layout, named dialog_delete_account.

 

dialog_delete_account.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <EditText
        android:id="@+id/password_txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="password..."
        android:inputType="textPassword"
        android:layout_margin="20dp"/>
</LinearLayout>

This only consist of one EditText with the hint password... Create DeleteAccountDialog.java and put it in the DialogFragments folder.

 

DeleteAccountDialog.java

package com.frogitecture.authenticatedgoose.DialogFragments;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import com.frogitecture.authenticatedgoose.R;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

public class DeleteAccountDialog extends DialogFragment {

    public interface DeleteAccountListener {
        void onDeleteAccount(String password);
    }

    public DeleteAccountListener listener;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = requireActivity().getLayoutInflater();

        View view = inflater.inflate(R.layout.dialog_delete_account, null);
        final EditText passwordTxt = view.findViewById(R.id.password_txt);

        builder.setView(view)
                .setTitle("Delete account")
                .setMessage("Are you sure you want to delete your account? This action cannot be undone")
                .setPositiveButton("Delete Account", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        String password = passwordTxt.getText().toString();
                        listener.onDeleteAccount(password);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
        return builder.create();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        try {
            listener = (DeleteAccountListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString() + " must implement the listener you silly goose");
        }
    }
}

We got an interface as usual, DeleteAccountListener with the method onDeleteAccount(String password) that is called when the user click on the Delete account button in the dialog. In MainActivity.java, we make the dialog show up when people click on the Delete account option in the toolbar:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        ...

        case R.id.delete_account:
            DeleteAccountDialog deleteAccountDialog = new DeleteAccountDialog();
            deleteAccountDialog.show(getSupportFragmentManager(),"Delete account");
            break;
        ...
    }
}

And we implement the listener:

public class MainActivity extends AppCompatActivity implements
        ChangeDisplayNameDialog.ChangeDisplayNameListener, ChangeEmailDialog.ChangeEmailListener,
        ChangePasswordDialog.ChangePasswordListener, DeleteAccountDialog.DeleteAccountListener {

        ...

}

And we implement the method:

@Override
public void onDeleteAccount(String password) {
    loadingDialog.setMessage("Deleting account...");
    loadingDialog.show(getSupportFragmentManager(),"Deleting Account");

    String currentEmail = firebaseUser.getEmail();
    AuthCredential credential = EmailAuthProvider.getCredential(currentEmail, password);

    firebaseUser.reauthenticate(credential)
            .addOnCompleteListener(new OnCompleteListener<Void>() {

                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        firebaseUser.delete()
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if (task.isSuccessful()) {
                                            finish();
                                            startActivity(new Intent(MainActivity.this, AuthActivity.class));
                                        }
                                        loadingDialog.dismiss();
                                    }
                                });
                    } else {
                        Toast.makeText(MainActivity.this, "Authentication failed, wrong password?", Toast.LENGTH_LONG).show();
                        loadingDialog.dismiss();
                    }
                }
            });
}

We reauthenticate the user with AuthCredential by using the users email and the password that was just entered. If the correct password was entered, the users account is deleted by the method firebaseUser.delete(). If successful, we start the AuthActivity activity.

That's it for the Firebase Authentication series.

Author

authors profile photo

Articles with similar tags

thumbnail
Firebase Authentication - 7 - Change display name

Changing a display name in Android Studio with firebase auth

By Frogitecture

thumbnail
Firebase Authentication - 8 - Change email

Changing email in Android with Firebase Authentication

By Frogitecture

thumbnail
Firebase Authentication - 9 - Change password

Changing a password in Android with Firebase Authentication

By Frogitecture