0

I am trying to add an Item under a Collection in Firebase.

Firebase Real Time Database

I am adding an Item and the Key is being assigned a value of null. I want to be able to add the Item below the Key for collection5. So I need a way to make the Key get the Value of collection5's Key.

There is a Recycler View which displays added Collections to a Logged In User. After clicking on a Collection the User is taken to a Recycler View for Items. This is where they are able to access the CreateItemActivity.

These are declarations at the top of my CreateItemActivity:

String[] collectionsList = new String[6];
    int a = 0;

The following code is below the OnCreate Method:

mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("User/" + uid + "/CollectionList/"+ collectionsList[a] );
mDatabaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        while (a <= 1) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                System.out.println(postSnapshot.getKey());
                key = postSnapshot.getKey();
                Toast.makeText(CreateItemsActivity.this, postSnapshot.getKey(), Toast.LENGTH_SHORT).show();
                collectionsList[a] = dataSnapshot.child(key).getKey();
            }
            a = a + 1;
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        Toast.makeText(CreateItemsActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
        throw databaseError.toException();
    }
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    You should push data: [see this post](https://stackoverflow.com/a/28822372/10352461) – Stefan de Kraker Jun 29 '22 at 13:12
  • Did you try calling `FirebaseDatabase.getInstance().getReference().child("User/" + uid + "/CollectionList").push().setValue(theNewList)` to add the new data? – Frank van Puffelen Jun 29 '22 at 14:26
  • Firebase API is asynchronous. So you might be interested in reading this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5). – Alex Mamo Jul 06 '22 at 09:30

0 Answers0