Saransh Agarwal
Saransh Agarwal

Reputation: 305

Getting the timestamp wrong firebase android

Hey I am trying to get the current TIMESTAMP in the app when clicking a button but the TIMESTAMP is incorrect. The TIMESTAMP sometimes shows the time ahead and sometimes 10 minutes before time. Here is the code

timestapmReference.addValueEventListener(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {
        final long timeStampLong = (long) dataSnapshot.child("time").child("timestampQuestionSeen").getValue();
        final DatabaseReference questionSeenReference = FirebaseDatabase.getInstance().getReference().child("users").child(uid).child("questions").
                child(imagename);

        questionSeenReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (!dataSnapshot.hasChild("questionSeen")) {

                    questionSeenReference.child("questionSeenTime").setValue(timeStampLong);
                    questionSeenReference.child("questionSeen").setValue("1");


                }
                questionSeenReference.removeEventListener(this);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        timestapmReference.removeEventListener(this);
    }


    public void onCancelled(DatabaseError databaseError) {

    }
});
    timestapmReference.child("time").child("timestampQuestionSeen").setValue(ServerValue.TIMESTAMP);

Upvotes: 0

Views: 337

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Your problem is that you are setting those values insider the onDataChange method. There is no need to do such a thing. Move this 2 lines:

questionSeenReference.child("questionSeenTime").setValue(timeStampLong);                                        
questionSeenReference.child("questionSeen").setValue("1");

outside that method and remove that listener because is useless. To set a value you only need to use the setValue() method directly on the reference.

Hope it helps.

Upvotes: 1

Related Questions