检查Firebase数据库中是否存在数据的正确方法是什么?

时间:2017-11-09 07:40:59

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

我是Firebase新手我最近在我的应用中添加了Firebase身份验证。 我在Firebase数据库中有一个单独的用户表。我想要检查用户表是否有一个具有特定UID的用户。 如果用户存在,我想检查用户状态是已启用还是已禁用。这是我的用户表: -

enter image description here

这里的Key是来自身份验证表的UID。这是我检查用户是否存在的代码。

    private boolean checkIfUserExists(final String userId){

        // Get a reference to our posts
        final FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference().child("Users").child(userId);

// Attach a listener to read the data at our posts reference
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.hasChild("status")) {


                    isAvailable = true;
                }else{

                    isAvailable = false;

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.println("The read failed: " + databaseError.getCode());
            }
        });

        return isAvailable;
    }

如果用户存在代码,这就是我调用的地方。

    private void firebaseAuthWithGoogle(GoogleSignInAccount account) {

        Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
//                            Toast.makeText(SignInActivity.this, user.getUid(), Toast.LENGTH_SHORT).show();

                            if (checkIfUserExists(user.getUid()))
                            {
                                Toast.makeText(SignInActivity.this, "User already exists", Toast.LENGTH_SHORT).show();

                            }else{
                                addNewUser(user.getUid(),user.getDisplayName(),user.getEmail(),userStatus);
                            }

                            if (checkUserStatus(user.getUid()))
                            {
                                Intent intent = new Intent(SignInActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            }else {
                                DisableProgress();
                                Toast.makeText(SignInActivity.this, "Please contact ACK to activate your account", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(SignInActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();

                        }

                        // ...
                    }
                });
    }

添加新用户的代码。

  private void addNewUser(String userId, String name, String email, String 
  status) 
  {
User user = new User(userId,name,email,status);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");

mDatabase.child(userId).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
            //Toast.makeText(SignInActivity.this, "User saved", Toast.LENGTH_SHORT).show();


        } else {
            Toast.makeText(SignInActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
        }
    }
});

}

感谢任何帮助或建议。谢谢。

1 个答案:

答案 0 :(得分:0)

您当前的方法并不错:您正在为特定用户加载节点,然后在客户端代码中检查其状态。

一个小的改进是将用户状态的整个检查移动到查询中:

private boolean checkIfUserExistsAndHasStatus(final String userId){

    // Get a reference to our posts
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference().child("Users").child(userId);
    Query query = ref.orderByChild("status").startAt("-");

    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                isAvailable = true;
            }else{
                isAvailable = false;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            System.out.println("The read failed: " + databaseError.getCode());
        }
    });

    return isAvailable;
}

这使用的带宽更少,因为它只加载状态节点。虽然不是很多,但每一点都有帮助。 : - )