Phantomazi Phantomazi - 1 month ago 12
Android Question

Check for duplicates before insertion in Firebase

I am new to Firebase and I trying to implement it into an Android application. It was all going well until now. I have to check the records for duplicates before inserting them and even after the tons of tutorials I watched online I can't figure it out.

I tried with rules, but apparently I was not able to write them down in a way they would work. I tried with

push()
, but this was not working either.

At the moment this is the code that I have:

private void updateDatabase(String year, String courseOfStudent, String workshopGroup, String day, String time, String lecture){
try{
mDatabase.child("student-timetables").child("course-of-student").setValue(courseOfStudent);
mDatabase.child("student-timetables").child(courseOfStudent).child("year").setValue(year);
mDatabase.child("student-timetables").child(courseOfStudent).child(year).child("workshop-group").setValue(workshopGroup);
mDatabase.child("student-timetables").child(courseOfStudent).child(year).child(workshopGroup).child("day").setValue(day);
mDatabase.child("student-timetables").child(courseOfStudent).child(year).child(workshopGroup).child(day).child("time").setValue(time);
mDatabase.child("student-timetables").child(courseOfStudent).child(year).child(workshopGroup).child(day).child(time).child("lecture").setValue(lecture);}
catch (Exception e)
{
Toast.makeText(getContext(), "Internal error occurred, please try again.", Toast.LENGTH_LONG).show();
}
}


And the rules from the Firebase console:

{
"rules": {
".read": "true",
".write": "auth != null",
"course-of-student": {
"year": {
"workshop-group": {
"day":{
"time": {
".write": "!data.exists()"
}
}
}
}
}
}
}


As of now what happens is that if there is a lecture detail at a specific time and I try to create a new record for this time the previous one gets overwritten. I want to reject this and display a message instead.

Where am I wrong?

Answer

First, add "ListenerForSingleValueEvent", and only then save the data in Firebase (if not exist..) For example:

mDatabase.child("student-timetables").child(courseOfStudent).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
     if(!(snapshot.child("year").exist))
    mDatabase.child("student-timetables").child(courseOfStudent).child("year").setValue(year);
   else
   Toast.maketext....."year exist.."

     if(!(snapshot.child(year).child("workshop-group").exist))
    mDatabase.child("student-timetables").child(courseOfStudent).child(year).child("workshop-group").setValue(workshopGroup);
   else
   Toast.maketext....."workshopGroup exist.."
    }
}
Comments