In my app I have to store students information having roll number attribute.I want to prevent users to enter duplicate roll number.So guide me how can I implement logic to ensure rollno to be unique. Image to reflect tree is as follows.
Asked
Active
Viewed 2,118 times
4
-
Use random number to generate roll number of each student – Fazal Hussain Apr 26 '18 at 09:46
-
Sir! These roll numbers are not system generated, these are entered by students explicitly.My motive is to learn about unique constraint on 'roll_no' child of all nodes of1th_role. – Rai Mashhood Qadeer Bhatti Apr 26 '18 at 09:51
-
Another option could be to change your datastructure to have a list of roll numbers (as keys) with userid as value – André Kool Apr 26 '18 at 10:36
-
Making a property value unique requires that you: 1) add a data structure where you use those values as the keys (this automatically ensures they're unique), 2) use a transaction or multi-location update when updating these value. For more on this see: https://stackoverflow.com/q/35243492, https://stackoverflow.com/q/41443767, https://stackoverflow.com/q/25294478, https://stackoverflow.com/q/39149216 – Frank van Puffelen Apr 26 '18 at 13:26
1 Answers
2
Try the following:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("user_detail").child("1th_role");
ref.orderByChild("roll_no").equalTo(number_entered).addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exist() {
Toasty.makeText(Activity_Name.this,"Number already exists",Toast.LENGTH_SHORT).show();
}
else{
//add data
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Since the student will enter the number, then do a query orderByChild("roll_no").equalTo(number_entered)
that checks if the roll number that is entered already exists in the database.

Peter Haddad
- 78,874
- 25
- 140
- 134
-
1Thanks a lot .It works for me.But Sir is there any way to implement constraints on a child on server side. Instead of checking for child on client side. – Rai Mashhood Qadeer Bhatti Apr 26 '18 at 10:25
-
-
2Sir! I have worked on mysql. And as we specifiy unique value constraint on a table field while creating a table that is why I expecting that feature in firebase. – Rai Mashhood Qadeer Bhatti Apr 26 '18 at 10:31
-
oh okay, yes there is no concept of primary key/unique constraint in firebase. It is also nosql – Peter Haddad Apr 26 '18 at 10:38