Open In App

How to Delete a Firebase User from Android App?

Improve
Improve
Like Article
Like
Save
Share
Report

We have seen in many of the apps that if have the choice to delete the user or can say your account permanently. Here we are going to see how we can implement that in our app and can delete our account permanently from the firebase authentication. Here while writing our code we will remove the user but before that, we will reAuthenticate the user.

Step by Step Implementation

Step 1: If you are new to Firebase then you can Refer to User authentication using Firebase in Android.

Step 2: Follow all the steps and “Login In” to your android app. Then create a mainmenu.xml file as following

XML




<?xml version="1.0" encoding="utf-8"?>
  
    <item
        android:id="@+id/menulogout"
        android:title="Logout" />
    
    <item
        android:id="@+id/delete"
        android:title="Delete User" />
      
</menu>


Step 3: Create a new empty activity and name the activity as DeleteUser

Step 4: Then Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file.

Java




import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.tabs.TabLayout;
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 mAuth;
  
    private ViewPager mviewPager;
    private FirebaseAuth firebaseAuth;
    private Toolbar mtoolbar;
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private TabLayout mTabLayout;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAuth = FirebaseAuth.getInstance();
        mtoolbar = (Toolbar)findViewById(R.id.main_page_toolbar);
    }
  
    @Override public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.mainmenu, menu);
        return true;
    }
  
    @Override
    public boolean
    onOptionsItemSelected(@NonNull MenuItem item)
    {
        super.onOptionsItemSelected(item);
        if (item.getItemId() == R.id.menulogout) {
            FirebaseAuth.getInstance().signOut();
            senttostart();
        }
        if (item.getItemId() == R.id.delete) {
            startActivity(new Intent(MainActivity.this, DeleteUser.class));
        }
        return true;
    }
}


Step 5: Working with the activity_deleteuser.xml file

Navigate to the app > res > layout > activity_deleteuser.xml and add the below code to that file. Below is the code for the activity_deleteuser.xml file. We will create two simple EditText and a Button.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".DeleteUser">
  
    <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" />
  
    <Button
        android:id="@+id/submit"
        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="227dp"
        android:background="@color/colorPrimary"
        android:text="Submit Here"
        android:textSize="15dp" />
      
</RelativeLayout>


Step 4: Working with the DeleteUser.java file

Go to the DeleteUser.java file and refer to the following code. Below is the code for the DeleteUser.java file. Comments are added inside the code to understand the code in more detail.

Java




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 androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
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 DeleteUser extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delete_user);
        final EditText email = findViewById(R.id.email);
        final EditText password = findViewById(R.id.logpass);
        Button submit = findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteuser(email.getText().toString(), password.getText().toString());
            }
        });
    }
  
    private void deleteuser(String email, String password) {
          
        final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
  
        // Get auth credentials from the user for re-authentication. The example below shows
        // email and password credentials but there are multiple possible providers,
        // such as GoogleAuthProvider or FacebookAuthProvider.
        AuthCredential credential = EmailAuthProvider.getCredential(email, password);
  
        // Prompt the user to re-provide their sign-in credentials
        if (user != null) {
            user.reauthenticate(credential)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            user.delete()
                                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            if (task.isSuccessful()) {
                                                Log.d("TAG", "User account deleted.");
                                                startActivity(new Intent(DeleteUser.this, StartActivity.class));
                                                Toast.makeText(DeleteUser.this, "Deleted User Successfully,", Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    });
                        }
                    });
        }
    }
}


Output: 



Last Updated : 12 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads