Reputation: 476
I'm making an app to store user data into Firebase realtime database. I've successfully saved and retrieved data to and from firebase database. Now suppose user have stored his name in database. Then i want to check if the name exists or not.
And if it exists, then is that name the same as the name stored in a string in my app or not?
Any idea? How to do this.
Code used for saving user's name
databaseReference.child("users").child(uniqueID).setValue(name);
Is there any way to get this specific value from database? Like is there anything like getValue()
or something?
Below is the screenshot of my app:-
Here is the sequence of my ap:- First user will register, then login. When user login for the first time, we will ask him to set a 4 digit passcode which will be stored in firebase database.
This is how i store the passcode. now when user will click on "SET", we will save entered passcode to database and redirect user to mainActivity. But when user will reopen our app, we will check if there is any passcode stored in our database for this particular user or not. If passcode is stored then we will directly send him to passcode verification activity where user will enter passcode and we have to check if the passcode in out and the user entered passcode is same or not. but if there is no passcode in database then we will open this Setup Passcode activity again and ask him to set up a passcode.
Upvotes: 0
Views: 2356
Reputation: 2375
Yes, you can use orderByChild()
query along with equalTo()
to check whether the data of the user exists in database or not.
This code not only checks if the passcode is present but also that it is correct or not.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("password").child("passcodes");
ref.orderByChild("passcode").equalTo(passCodeYouHave).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
// passcode is present, and is correct
else
// incorrect passcode or no passcode
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Here passCodeYouHave
is the passcode of the user you have in the app, and you can use it to check in firebase, if such name exists in the node named passcode
.
This code will not check the correct passcode, it will just check if there is a passcode or not.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("password").child("passcodes");
ref.orderByChild("passcode").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
// passcode is present, so go to activity for checking the passcode
else
// no passcode is present so go for activity to set up new passcode
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Upvotes: 1