Home > Mobile >  Duplicate child when i call push() in Firebase Realtime Database
Duplicate child when i call push() in Firebase Realtime Database

Time:12-17

I am trying to retrieve data from Firebase Realtime Database and add this data to a listview. When I call push() firebase generates two children (one inside the other) with the same unique key. This is the structure of my database:

database

That is how I save the data:

RunningSession runningSession = new RunningSession(date, activityTime, pace, timeElapsed,
                                finalDistance, image, tipe);

DatabaseReference reference = databaseReference.child("users").child(userUid).child("activities").push();

Map<String, Object> map = new HashMap<>();
map.put(reference.getKey(),runningSession);
reference.updateChildren(map);

This is how i retrieve the data (results in a null pointer exception):

DatabaseReference reference = databaseReference.child("users").child(userId).child("activities");
reference.addValueEventListener(new ValueEventListener() {
       @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
             list.clear();
             for (DataSnapshot snpshot : snapshot.getChildren()) {
                    RunningSession run = snpshot.getValue(RunningSession.class);
                    list.add(run);
             }
        }

       @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
   });

   ListViewAdapter adapter = new ListViewAdapter(this, list);
   ListView activityItems = (ListView) findViewById(R.id.activityList);
   activityItems.setAdapter(adapter);

CodePudding user response:

You are getting duplicate push IDs because you are adding them twice to your reference. If you only need one, then simply use the following lines of code:

RunningSession runningSession = new RunningSession(date, activityTime, pace, timeElapsed, finalDistance, image, tipe);
DatabaseReference reference = databaseReference.child("users").child(userUid).child("activities");
String pushedId = reference.push().getKey();
reference.child(pushedId).setValue(runningSession);

The code for reading that may remain unchanged.

  • Related