Abdullah Yahya
Abdullah Yahya

Reputation: 127

Firebase Database onDataChange not working sometimes

I have this structure:

"notifications" : {
"-KxoRpDJw6qt4kb1d4Ad" : {
  "11B Boys" : {
    "-L5QX6mvUI7Eed_FDK8R" : {
      "body" : "hello",
      "sender" : "h0ClA5VusLZMTDR6iyI4OAjLzm43",
      "title" : "hi"
    }
  },
  "All" : {
    "-L5QB_D6n_G8B5si5zMd" : {
      "body" : "d5d5",
      "sender" : "h0ClA5VusLZMTDR6iyI4OAjLzm43",
      "title" : "d5f6"
    },
    "-L5QBj31bF5On3xOIiM9" : {
      "body" : "hfhfy",
      "sender" : "h0ClA5VusLZMTDR6iyI4OAjLzm43",
      "title" : "gdgdhc"
    }
  }

my problem that onDataChange returns first block of notifications correctly ( messesge with "hello" body and "hi" title) other messages are not returned well (their keys are returned successfully) but it seems that they are considered as null .

heres the code:

           final String notificationDetails[] = token.split(";");
    ValueEventListener valueEventListener = new ValueEventListener() {
         @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
                tvTitle.setText(dataSnapshot.child("title").getValue(String.class));
                tvBody.setText(dataSnapshot.child("body").getValue(String.class));

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    } ;
                                                                    // school_id->topic->notification_id
    FirebaseDatabase.getInstance().getReference("notifications").child(notificationDetails[0]).child(notificationDetails[1])
    .child(notificationDetails[2]).addValueEventListener(valueEventListener);

Upvotes: 1

Views: 985

Answers (2)

Abdullah Yahya
Abdullah Yahya

Reputation: 127

found the answer my self, I don't know why but when inserting entries using setValue() i must send the whole node one time.

Inserting:

ref.setValue(obj); // of type notification

Instead of:

ref.child("title").setValue("my title");
ref.child("body").setValue("my body");

Upvotes: 3

Koushik Shom Choudhury
Koushik Shom Choudhury

Reputation: 856

Remove the child(notificationDetails[2]) from the reference because you need to listen to changes in '11B Grade' to retrieve all the changes made to it. Currently you are listening to a child of '11B Grade'.

FirebaseDatabase.getInstance().getReference("notifications").child(notificationDetails[0]).child(notificationDetails[1]). addValueEventListener(valueEventListener);

Upvotes: 0

Related Questions