muhammad obaid
muhammad obaid

Reputation: 117

How to check if key already exists in firebase

I am working on an attendance management system. I would like it to show a toast message if the user's attendance has been already marked for the current date, otherwise I would like to set their attendance.

I am using new date as attendance key.Now I want to check if the new date is already in the node.

You can see the format of my database in the image below.

Database Image

Now in the addValueEventListener I would like to check if the current date is available and upload the attendance otherwise show the toast stating that the attendance has been already marked.

How do I do that?

AttendRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for (DataSnapshot child : dataSnapshot.getChildren()) {

            if (child.child(date).getKey().equals(date)){
                Toast.makeText(ProfileAct.this, "Already marked", Toast.LENGTH_SHORT).show();
            }
            else {
                AttendRef.child(date).setValue("Present");
            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

Upvotes: 0

Views: 1162

Answers (1)

samthecodingman
samthecodingman

Reputation: 26171

Because you've missed some information in your question, I have made the following assumptions:

  • You are looking up attendance for a user's ID stored in the string userId on the date stored in the string date.
  • AttendRef is a DatabaseReference that points to Users/{userId}/Attendance
  • The given date is the only date looked up and changed for the given user ID.

Firstly, I would strongly recommend changing the way you store dates to the ISO 8601 format. In Java, this is given by the format "yyyy-MM-dd". The reason for this is that the dates will then be sorted correctly by Firebase from oldest to newest.

Based on your question and the assumptions above, you can just query the data in the database directly rather than wastefully downloading all the data under "Attendance" and then iterating through it.

SimpleDateFormat DB_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
DatabaseReference DB_ROOT_REF = FirebaseDatabase.getInstance().getReference();

String userId = "bq7TqEwgluSiNRP7FDKanHptd9C2"; // the user to lookup
String date = DB_DATE_FORMAT.format(new Date()); // save attendance for today's date

DatabaseReference AttendRef = DB_ROOT_REF.child("Users").child(userId).child("Attendance");

AttendRef.child(date).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        // If data exists, toast currently stored value. Otherwise, set value to "Present"
        if (dataSnapshot.exists()) {
            Toast.makeText(ProfileAct.this, "Already marked as '" + dataSnapshot.getValue(String.class) + "'", Toast.LENGTH_SHORT).show();
        } else {
            dataSnapshot.getRef().setValue("Present");
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        //TODO: Handle this
    }
});

In the above code, use of addListenerForSingleValueEvent(...) is important, otherwise this listener will trigger itself because of setValue(...).

Further Reading

Upvotes: 1

Related Questions