当用户关闭应用程序时,从Firebase Realtime数据库中删除数据 [英] Delete data from Firebase Realtime Database when user closes app

查看:54
本文介绍了当用户关闭应用程序时,从Firebase Realtime数据库中删除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android开发人员和Firebase的新手.

I'm very new to Android dev and Firebase.

我需要以下帮助:

用户通过Firebase密码身份验证进行身份验证(片段称为SignUp)后,将其另存为实时数据库中的用户-> UID->个人电子邮件,然后移动到新片段-AddUsername片段.该片段要求唯一的用户名.

After a user authenticates with Firebase Password Authentication (fragment is called SignUp), this is saved as users->UID->person's email in the Realtime Database.Then, they move to a new fragment - AddUsername fragment. This fragment asks for a unique username.

我要实现的目标是,如果用户不输入用户名就退出并关闭应用程序,则从Firebase控制台中删除了实时数据库中保存的数据,并将用户带回注册"片段以重新启动注册过程.这样可以防止创建无效的电子邮件帐户或错误地退出"并且无法重复使用电子邮件地址的帐户.

What I am trying to achieve is if a user exits and closes the app without entering a username, the saved data from the Realtime Database is deleted from the Firebase Console and the user is taken back to the Sign Up fragment to restart the registration process. This prevents the creation of inactive email accounts or accounts that was mistakenly "exited" and the email address cannot be reused.

到目前为止,这是我的代码,我不知道需要什么代码来完成此操作.

This is my code so far and I do not know what code I need to accomplish this.

我已将此代码添加到AddUsername片段的onDestroyView()上.当我按下后退"按钮时,实时数据库中的数据将被删除,但是当我关闭该应用程序时,该数据不会被删除.

I've added this code on the onDestroyView() of AddUsername fragment. The data in the Realtime Database gets deleted when I press back the Back button but when I close the app, the data does not get deleted.

 @Override
public void onDestroyView() {
    super.onDestroyView();


    mAuth.signOut();

    mDatabase.child("users").child(user.getUid()).removeValue();
    Log.i("User: ", "Not saved in database");

    user.delete()
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "User account deleted.");

                    }


                }



            });

}

谢谢.

公共类AddUsername扩展Fragment实现View.OnClickListener,TextWatcher {

public class AddUsername extends Fragment implements View.OnClickListener, TextWatcher {

public AddUsername() {

}


public interface FragmentComm {
    void toSetName();
}

private TextView title, headings, handleError;
private EditText addUsername;
private Button nextButton;
private String getUsername;
private FirebaseAuth mAuth;
private FirebaseUser user;
private DatabaseReference mDatabase;
private FragmentComm fragmentComm;

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

    fragmentComm = (FragmentComm) getActivity();
    user = FirebaseAuth.getInstance().getCurrentUser();
    mAuth = FirebaseAuth.getInstance();
    mDatabase = FirebaseDatabase.getInstance().getReference();

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.add_username, container, false);

    title = view.findViewById(R.id.username_title);
    headings = view.findViewById(R.id.display_user_message);
    handleError = view.findViewById(R.id.message_error);
    addUsername = view.findViewById(R.id.addUsername);
    nextButton = view.findViewById(R.id.nextButton);
    nextButton.setOnClickListener(this);
    addUsername.addTextChangedListener(this);


    return view;
}


@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

}


@Override
public void afterTextChanged(Editable s) {


    getUsername = addUsername.getText().toString();

    if (getUsername.isEmpty()) {

        handleError.setVisibility(View.GONE);
        nextButton.setBackgroundColor(Color.parseColor("#EEEEEE"));
        nextButton.setTextColor(Color.parseColor("#BDBDBD"));
        nextButton.setEnabled(false);


    } else {

        Query query = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo(getUsername);
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {

                    handleError.setText(R.string.username_not_available);
                    handleError.setVisibility(View.VISIBLE);
                    handleError.setTextColor(Color.parseColor("#F50057"));
                    nextButton.setBackgroundColor(Color.parseColor("#EEEEEE"));
                    nextButton.setTextColor(Color.parseColor("#BDBDBD"));
                    nextButton.setEnabled(false);

                } else {

                    handleError.setText(R.string.username_available);
                    handleError.setVisibility(View.VISIBLE);
                    handleError.setTextColor(Color.parseColor("#26C485"));
                    nextButton.setBackgroundColor(Color.parseColor("#0277BD"));
                    nextButton.setTextColor(Color.parseColor("#FFFFFF"));
                    nextButton.setEnabled(true);

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.i("Give info", "Error");


            }
        });

    }

}


@Override
public void onClick(View v) {

    switch (v.getId()) {

        case R.id.nextButton:

            checkUsernameAlreadyExist();

    }


}

private void checkUsernameAlreadyExist() {

    getUsername = addUsername.getText().toString();


    Query query = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo(getUsername);
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {

                handleError.setText(R.string.username_not_available);
                handleError.setVisibility(View.VISIBLE);
                handleError.setTextColor(Color.parseColor("#F50057"));


            } else {

                handleError.setText(R.string.username_available);
                handleError.setVisibility(View.VISIBLE);
                handleError.setTextColor(Color.parseColor("#26C485"));

               fragmentComm.toSetName();
                setDatabaseName();

            }
        }


        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.i("Give info", "Error");


        }
    });

}


private void setDatabaseName() {

    mDatabase.child("users").child(user.getUid()).child("username").setValue(getUsername);


}

推荐答案

我认为这对于 onDisconnect 处理程序可能是一个很好的用例.这些是应用程序在连接时发送到Firebase数据库的写指令,一旦检测到客户端消失,数据库服务器便会执行.

I think this might be a good use-case for an onDisconnect handlers. These are write instructions that an app sends to the Firebase Database when it's connected, that the database server then executes once it detects that the client is gone.

一个例子:

private void setDatabaseName() {
  DatabaseReference usernameRef = mDatabase.child("users").child(user.getUid()).child("username");
  usernameRef.setValue(getUsername);
  usernameRef.onDisconnection().removeValue();
}

有关更多信息,请参见关于 onDisconnect 处理程序.

For more on this, see the Firebase documentation on onDisconnect handlers.

这仅适用于数据库.您可能必须找到另一种方法来清理Firebase身份验证帐户.

This will only work for the database though. You might have to find another way to also clean up the Firebase Authentication account.

还要注意,您用来确保唯一用户名的方法不是很有效.有关更惯用的方法,请参见:

Also note that the approach you're taking to ensure unique usernames is not very efficient. For a more idiomatic approach, see:

这篇关于当用户关闭应用程序时,从Firebase Realtime数据库中删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆