0

Getting undefined value in firebase when pushing the new node through android code but when adding manually means in firebase database directly then I am getting data. Unable to figure out what's wrong here.

exports.onUserCreated = functions.database.ref('/fcm/{pushId}')
    .onCreate((snapshot, context ) => {
      // Do something when a new user is created
      var email = snapshot.val().userid;
      var name = snapshot.val().username;
      var score = snapshot.val().desc;

      console.log(name);
      console.log(email);
      console.log(score);

      return sendWelcomeEmaill(email, name, score);
    });

function sendWelcomeEmaill(email, name, score){
    const mailOptions = {
        from :  `${APP_NAME} <[email protected]>`,
        to: email,
      };

    mailOptions.subject = `Score in Quiz ${APP_NAME}!`;
    mailOptions.html = `Hey ${name || ''}! Your score in ${APP_NAME} Quiz is ${score}.<br />
    <img src="https://lh3.googleusercontent.com/5gapf20jRXFQ7XchrHByzUDQfZUPccJ417emPwHJNlY72dcazXi_X3urzAGq3f2rXPjlNlZmxj0fuiy88tJ3exVQuA6XEt6Dm4kFlq1efWtWh3f1gMZ8humwKjds3uWX-a8kxODCNym7xfT9CwjwPMGy_LapGBbdwbxn2v0KdgCW12gHXOElqRmSKCOZlLRVVQ5FrFkwjm4rp9EtbJngPbOASMoAVVGMucfsMRqX2KHRpKnvgsvDw4v8I7EgyvlF_59eAsnjUclzZHbTR7PMSDes9RC883H6h2oWt6ZiJ5--cp1dijI0-zap5M30RvCQzSXKAoDX1CkuwhRuzkBSa4ffYa1uq9Z38IcGxPFzZcyKMSG1sc7XRQE1oxSedkx8knlX46194-nyqkwxxVwvas3emTgPpGH_AjaW1BAZPLJl4B8Sks3hQg8S9gF492dNppgFiZV6pGELZ2glbQDD8o5S-Lj9vtYUjQb1tu9892zxPEqkGwqaVZ2buFnNgPm3iZKi8jS7WpjIzvJoXsMJ8y9LoT7l8N5xStOTMa6MKsol3-lT89y3UHHflPFmdHV42K_HnGi806_iNvFlgo5Czg0ZYBXCicwJCryu6ND2qASEQCIbHOVBmzyqUK-BhTj4HzDuHsIu_j7WJITqowxEleI=w69-h52-no">
    <br/>We hope you will enjoy our service. <br/> `;

    return mailTransport.sendMail(mailOptions).then(() => {
      return console.log('New welcome email sent to:', email);
    });
}

Wait but getting the userid in both the methods . If my question is not clear please ask me in comment.

Case 1 screenshot [when adding data through android code]

enter image description here

Case2 screenshot when adding manually [working]

enter image description here

Here is my android code for pushing data in firebase

mDatabase3 = FirebaseDatabase.getInstance().getReference().child("fcm");

mDatabaseUser1.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                // long i =  -1* new Date().getTime();

                //  String user_id = mAuth.getCurrentUser().getUid();

                String id = acct.getEmail();
                Uri personPhoto = acct.getPhotoUrl();

                final DatabaseReference newPost3 = mDatabase3.push();

                //  high.child(cleanEmail).setValue(finalValue);

                //high.child(node).setValue(finalValue);


                // newPost3.child(user_id).child("time").setValue(ServerValue.TIMESTAMP);
                // newPost3.child(user_id).child("uid").setValue(mCurrentUser.getUid());
                newPost3.child("userid").setValue(acct.getEmail());

                newPost3.child("desc").setValue(finalValue);
              //  newPost3.child("userimage").setValue(personPhoto.toString());
                newPost3.child("username").setValue(acct.getDisplayName()).addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {

                        if (task.isSuccessful()) {



                        }


                    }
                });

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
15
  • You should share the Android code used to "push the new node" and not only the Cloud Function code. Do you see the data pushed by the Android app in the database console? Commented Jan 18, 2019 at 9:11
  • Yep @RenaudTarnec android code is pushing the data in write way Commented Jan 18, 2019 at 9:12
  • And you confirm that when you add the data manually through the console it does works perfectly? Commented Jan 18, 2019 at 9:14
  • Yep @RenaudTarnec I just checked again by adding data manually and it is working Commented Jan 18, 2019 at 9:15
  • 1
    If the problem only happens when you add the data through your Android code, share the Android code that adds the data. Commented Jan 18, 2019 at 15:10

1 Answer 1

2

Each time you call setValue() or updateChildren() in a reference it results in data being written to the database. This means that in your code, the new node for the new user gets created after these statements:

final DatabaseReference newPost3 = mDatabase3.push();

newPost3.child("userid").setValue(acct.getEmail());

So at that point, the database only contains a userid for the new node. Since the node is now created, your Cloud Function gets triggered and username and score will be undefined at this point.

To prevent this from happening, you need to write the entire node for the new user in one call to the database. A simple way to do this, is to put all data in a HashMap:

Map<String, Object> values = new HashMap<String, Object>();

values.put("userid", acct.getEmail());
values.put("desc", finalValue);
values.put("username", acct.getDisplayName());

mDatabase3.push().setValue(values);
Sign up to request clarification or add additional context in comments.

4 Comments

Sir you are genius I struggled for more than 12 hours for this issue and you solved it one go. Thank you so much . My one request if you found this question helpful for future visitors please up vote this question.
Well spotted Frank!
@Frank you mean when newPost.child("userid").setValue(acct.getEmail()); add in database it triggers the functions and that's the reason the other child values are not reachable by cloud function ???
Yes, that's precisely it. Give it a try: run the Android code that creates a node through a debugger and step through the setValue() statements. You'll see that after the first setValue() the /fcm/{pushId} node is created already, and thus your Cloud Function gets triggered with only the child property that exists at that time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.