I need help regarding checking if the value is already exists in the database so Users won't be able to change it to the same number when they're updating it, like a unique ID
I've been searching for hours for a solution but I can't find any that's working.
To achieve this, I recommend you create another node named userIds
. Every time a new user is created just add the user id in this new section. This new section should look like this:
Firebase-root
--- userIds
--- Id101: true
--- Id102: true
Then just put a listener on this new node node and use exists()
method on the dataSnapshot object.
As recommended before you should have a data structure, an index list, for this, why? Because when you have tons of this ids it will be a better query. However, I think what you are trying to do is complementary to the previous suggestions.
What you have to do is use a single event listener, if the datasnapshot is not null, then the value exists. The key is query the id you need:
DatabaseReference root = FirebaseDatabase.getInstance.getReference();
DatabaseReference reference = root.child("Test").oderByChild("ID").equalsTo(someId);
reference.addSingleValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnaphot != null) {
//This means the value exist, you could also dataSnaphot.exist()
}
}
//More auto generated code
);
The dataSnapshot
is a bunch of your objects, because the query could match more than one result. You can iterate inside of it if you need the value of each:
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnaphot != null) {
for (DataSnapshot children : dataSnaphot.getChildrens()) {
YourModel yourModel = children.getValue(YourModel.class);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.