4

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.

enter image description here

KENdi
  • 7,576
  • 2
  • 16
  • 31
  • 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 Answers1

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