1

Before posting the question I have seen many answers about my problem, But I was unable to understand the answer. So, I wanna know how can I check if a user Id from authentication is a database key or not?

CODE

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

As you can see the images I wanna check if User UID is a key or not in Firebase database

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
HARSH ASHRA
  • 176
  • 1
  • 4
  • 20

1 Answers1

2

You can check like this:

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) {

        }
    });

Exists Returns true if the snapshot contains a non-null value.

Kasım Özdemir
  • 5,414
  • 3
  • 18
  • 35