我想删除Firebase Auth上的选定用户

时间:2019-07-29 12:15:04

标签: android firebase firebase-realtime-database firebase-authentication

我要删除Firebase身份验证上的选定用户。

当前,我可以通过数据库删除当前所选用户的数据。但我也想从Auth部分删除用户。我可以在使用适配器之前执行此操作。但是使用适配器时我无法做到这一点。

我的AdminPanel适配器:

package com.example.yagoozonfirebasejava;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.List;

public class AdminPanelAdapter extends RecyclerView.Adapter<AdminPanelAdapter.CardDesingHolder> {

    private Context mContext;
    private List<Users> usersList;
    private DatabaseReference myRef;



    // Constructor
    public AdminPanelAdapter(Context mContext, List<Users> kisilerListe, DatabaseReference myRef) {
        this.mContext = mContext;
        this.usersList = kisilerListe;
        this.myRef = myRef;
    }
    // Holder class
    public class CardDesingHolder extends RecyclerView.ViewHolder {

        private TextView usernameAdmin;
        private TextView user_surnameAdminAdapter;
        private TextView user_emailAdminAdapter;
        private TextView user_RealnameeAdminAdapter;
        private TextView userUuidAdmin;
        private ImageView deleteUserAdmin;
        private FirebaseAuth mAuthAmdin;

        public CardDesingHolder(View itemView) {
            super(itemView);
            usernameAdmin = itemView.findViewById(R.id.username_AdminCard);
            user_RealnameeAdminAdapter = itemView.findViewById(R.id.userRealNameAdminCard);
            user_surnameAdminAdapter = itemView.findViewById(R.id.userSurnameAdminCard);
            user_emailAdminAdapter = itemView.findViewById(R.id.userEmail_AdminCard);
            userUuidAdmin = itemView.findViewById(R.id.userUuidAdmin);
            deleteUserAdmin = itemView.findViewById(R.id.imageViewDeleteUser);
        }
    }

    @Override
    public CardDesingHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.admin_usercard, viewGroup, false);
        return new CardDesingHolder(view);
    }

    @Override
    public void onBindViewHolder(final CardDesingHolder cardDesingHolder, int position) {
        final Users user = usersList.get(position);

        cardDesingHolder.user_emailAdminAdapter.setText("Mail : " + user.getUser_email());
        cardDesingHolder.user_surnameAdminAdapter.setText("Surname : " + user.getUser_surname());
        cardDesingHolder.user_RealnameeAdminAdapter.setText("Name : " + user.getUser_name());
        cardDesingHolder.usernameAdmin.setText("Username : " + user.getUser_username());
        cardDesingHolder.userUuidAdmin.setText("User UUID : " + user.getUser_id());

        // User Delete
        cardDesingHolder.deleteUserAdmin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final AlertDialog.Builder alert = new AlertDialog.Builder(mContext);

                alert.setTitle("Alert!");
                alert.setMessage("Are you sure??");

                alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, int which) {
                        // Delete User value's on Database
                        myRef.child(user.getUser_id()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(Task<Void> task) {
                                if(task.isSuccessful()) {
                                    Toast.makeText(mContext, "User Successfully Deleted!", Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                }
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(Exception e) {
                                Toast.makeText(mContext, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        });
                    }
                });

                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                alert.create().show();
            }
        });
    }


    @Override
    public int getItemCount() {
        return usersList.size();
    }
}

我的管理面板类:

package com.example.yagoozonfirebasejava;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Image;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

import static android.view.View.TEXT_ALIGNMENT_CENTER;

public class AdminPanel extends AppCompatActivity {

    private Toolbar toolbarAdmin;
    private RecyclerView recyclerViewAdminPanel;
    private ArrayList<Users> usersArrayList;
    private AdminPanelAdapter adapter;
    private FirebaseDatabase database;
    private DatabaseReference myRef;
    private FirebaseAuth mAuthAdmin;
    private Button btn_menu;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_panel);
        /*
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {
            // User is signed in
            Intent intent = new Intent(AdminPanel.this, ProfilePage.class);
            startActivity(intent);
            finish();

        } else {
            // No user is signed in
            Intent intent = new Intent(AdminPanel.this, MainActivity.class);
            startActivity(intent);
            finish();
        }*/


        // Firebase Auth
        mAuthAdmin = FirebaseAuth.getInstance();


        // Toolbar Settings //
        toolbarAdmin = findViewById(R.id.toolbarAdmin);
        toolbarAdmin.setTitle("Yagoozon - Admin Panel");
        toolbarAdmin.setSubtitle("Welcome Admin");
        // Menu
        toolbarAdmin.inflateMenu(R.menu.logout_menu);
        toolbarAdmin.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                String mesaj = "";
                switch (item.getItemId()) {
                    case R.id.logout_menuid:
                        mAuthAdmin.signOut();
                        Intent out = new Intent(AdminPanel.this, MainActivity.class);
                        startActivity(out);
                        finish();
                        mesaj = "User Sign out!";
                        break;
                }
                Toast.makeText(AdminPanel.this, mesaj, Toast.LENGTH_LONG).show();
                return true;
            }
        });
        // Toolbar Settings End  //

        // Menu Button //
        btn_menu = findViewById(R.id.btn_filterAdminPanel);
        btn_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popupMenu = new PopupMenu(AdminPanel.this, btn_menu);
                popupMenu.getMenuInflater().inflate(R.menu.filter_menu, popupMenu.getMenu());


                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.filterDate:
                                Query query = FirebaseDatabase.getInstance().getReference("Users")
                                        .orderByChild("user_email")
                                        .equalTo(mAuthAdmin.getCurrentUser().getEmail());

                                query.addValueEventListener(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {
                                        usersArrayList.clear();

                                        for (DataSnapshot d : dataSnapshot.getChildren()) {
                                            Users user = d.getValue(Users.class);
                                            user.setUser_id(d.getKey());

                                            usersArrayList.add(user);

                                        }

                                        adapter.notifyDataSetChanged();

                                    }

                                    @Override
                                    public void onCancelled(@NonNull DatabaseError databaseError) {

                                    }
                                });

                            return true;

                            case R.id.filterUuid:
                                Query queryUuid = FirebaseDatabase.getInstance().getReference("Users")
                                        .orderByChild("user_id")
                                        .equalTo(mAuthAdmin.getCurrentUser().getUid());

                                queryUuid.addValueEventListener(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {
                                        usersArrayList.clear();

                                        for (DataSnapshot d : dataSnapshot.getChildren()) {
                                            Users user = d.getValue(Users.class);
                                            user.setUser_id(d.getKey());

                                            usersArrayList.add(user);

                                        }

                                        adapter.notifyDataSetChanged();

                                    }

                                    @Override
                                    public void onCancelled(@NonNull DatabaseError databaseError) {

                                    }
                                });
                                return true;

                            case R.id.filterDefault:
                                myRef.addValueEventListener(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(DataSnapshot dataSnapshot) {

                                        usersArrayList.clear();

                                        for (DataSnapshot d : dataSnapshot.getChildren()) {
                                            Users user = d.getValue(Users.class);
                                            user.setUser_id(d.getKey());

                                            usersArrayList.add(user);

                                        }

                                        adapter.notifyDataSetChanged();

                                    }

                                    @Override
                                    public void onCancelled(@NonNull DatabaseError databaseError) {

                                    }
                                });
                                return true;
                            default:
                                return false;

                        }
                    }
                });
                popupMenu.show();
            }
        });


        // Menu Button End //

        // Definitions
        recyclerViewAdminPanel = findViewById(R.id.recyclerViewAdminPanel);

        // Firebase Database Connection
        database = FirebaseDatabase.getInstance();
        myRef = database.getReference("Users");


        // Recycler View
        recyclerViewAdminPanel.setHasFixedSize(true);
        recyclerViewAdminPanel.setLayoutManager(new LinearLayoutManager(this));

        // Create Array List
        usersArrayList = new ArrayList<>();

        // Recycler View Adapter
        adapter = new AdminPanelAdapter(AdminPanel.this, usersArrayList, myRef);
        recyclerViewAdminPanel.setAdapter(adapter);

        getUsersAdmin();

    }

    // Get Users Method
    public void getUsersAdmin() {

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                usersArrayList.clear();

                for (DataSnapshot d : dataSnapshot.getChildren()) {
                    Users user = d.getValue(Users.class);
                    user.setUser_id(d.getKey());

                    usersArrayList.add(user);

                }

                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    // Back Button
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finishAffinity(); // or finish();
    }
}

我的应用程序删除屏幕截图:

enter image description here

单击下面您要删除的垃圾桶图标。从数据库中删除该用户。但是它不会在Auth上删除。

我尝试了几种不同的方法,但是没有。从Auth删除时,我想从数据库中删除选定的用户数据。

1 个答案:

答案 0 :(得分:1)

以下代码可帮助我删除用户帐户。

对于Facebook

final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        try {
            AuthCredential credential = FacebookAuthProvider.getCredential(FirebaseAuth.getInstance().getCurrentUser().getProviderId());
            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.");
                                                    fbLogut();
                                                }
                                            }
                                        });

                            }
                        });
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

对于Google

try {
            AuthCredential credentialg = GoogleAuthProvider.getCredential(FirebaseAuth.getInstance().getCurrentUser().getUid(), null);
            // Prompt the user to re-provide their sign-in credentials
            if (user != null) {
                user.reauthenticate(credentialg)
                        .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.");
                                                    googleSignout();
                                                }
                                            }
                                        });

                            }
                        });
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

用于电子邮件验证:

AuthCredential credential = EmailAuthProvider
                    .getCredential(em, password);
            if (user != null) {
                user.reauthenticate(credential).addOnCompleteListener(task -> user.delete().addOnCompleteListener(task1 -> {
                                    if (task1.isSuccessful()) {
                                        Log.d("Tag", "User account deleted.");
                                    }
                                }));
            }

或(如果您是管理员)

FirebaseAuth.getInstance().deleteUser(uid);