如何检查Firebase数据库中是否存在密钥?

时间:2020-05-16 11:56:27

标签: android firebase firebase-realtime-database

在发布问题之前,我已经看到许多有关问题的答案,但是我无法理解答案。 因此,我想知道如何检查来自身份验证的用户ID是否为数据库密钥?

代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    user = FirebaseAuth.getInstance().getCurrentUser();
    db = FirebaseDatabase.getInstance().getReference().child("UserInfo");
    Thread mythread = new Thread() {
        public void run() {
            try {
                while (splashActive && ms < splashTime) {
                    if (!paused)
                        ms = ms + 100;
                    sleep(100);
                }
            } catch (Exception e) {
            } finally {
                if (user != null) {
                    if (user.getUid().toString().equals(/* How to check if key exists or not*/)) {
                        Intent intent = new Intent(MainActivity.this, Chat.class);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(MainActivity.this, UploadUserInfo.class);
                        startActivity(intent);
                    }
                } else {
                    Intent intent = new Intent(MainActivity.this, RegisterUser.class);
                    startActivity(intent);

                }
            }
        }
    };
    mythread.start();
}

}

enter image description here

enter image description here

您可以看到图像,我想检查Firebase数据库中用户UID是否为密钥

1 个答案:

答案 0 :(得分:1)

您可以像这样检查:

db.child(user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){
                // user exists in the database
                String userName = dataSnapshot.child("userName").getValue(String.class);
                Intent intent = new Intent(MainActivity.this, Chat.class);
                startActivity(intent);
            }else{
                // user does not exist in the database
                Intent intent = new Intent(MainActivity.this, UploadUserInfo.class);
                startActivity(intent);
            }
        }

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

        }
    });

存在如果快照包含非空值,则返回true。