Create a node inside another in Firebase with Android Studio

Asked

Viewed 70 times

0

I would like to create a node called "Posts" within each user, but I can only create outside the user. It could help me to create the node within the user?

Here is an example of how I wanted the "Posts" in firebase and how it is: inserir a descrição da imagem aqui

Here is the Android code that creates the "Posts":

    private void addPost(Post post) {

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("Posts").push();

    String key = myRef.getKey();
    post.setPostKey(key);

    myRef.setValue(post).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            showMessage("Adicionado com sucesso");
            popupClickProgress.setVisibility(View.INVISIBLE);
            popupAddBtn.setVisibility(View.VISIBLE);
            popAddPost.dismiss();

        }
    });

}
  • John. From a reformulated question so that it actually expresses its doubt..

  • Okay, reworked, thank you

1 answer

1


John, in order for the node to be created within the user you must reference it in the correct location, try using the following code:

 private void addPost(Post post) {

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.child('Users').child(USER_ID).child("Posts").push();

    String key = myRef.getKey();
    post.setPostKey(key);

    myRef.setValue(post).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            showMessage("Adicionado com sucesso");
            popupClickProgress.setVisibility(View.INVISIBLE);
            popupAddBtn.setVisibility(View.VISIBLE);
            popAddPost.dismiss();

        }
    });

}

  • Thank you, solved the problem

  • Magina, you understood where the problem was João?

  • Thanks, helped me a lot!!! Solved

  • Yes, I was forgetting to reference the path

  • I’m glad I could help :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.