2

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);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

2

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • It worked. Thanks! One more question: using onDataChange() the data are shown in the list only if I add a new activity. I would like to see the list when I open the app. How can I do that? – Andreea Nita Dec 17 '21 at 11:18
  • You should populate the list [only when the data becomes available](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method/47853774). – Alex Mamo Dec 17 '21 at 11:31