John
John

Reputation: 437

Android - getValue from Firebase returns null

I am setting the value of a child in Firebase, but when I get the value from Firebase the value is null. I don't understand why.

   database.child("User").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    int depositInteger = 0;
                    try {
                        depositInteger = Integer.parseInt(depositText.getText().toString().trim());
                    } catch (NumberFormatException e) {
                        if (depositText.equals("")) {
                            Toast.makeText(getActivity(), "Failed", Toast.LENGTH_SHORT).show();
                        }
                    }


                    database.child(user.getDisplayName()).child("deposit").setValue(depositInteger);
                    Long previousDeposit = dataSnapshot.child("User").child(user.getDisplayName()).child("deposit").getValue(Long.class);
                    System.out.println("VAAAALUE: " + previousDeposit);


                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

enter image description here

Upvotes: 0

Views: 1068

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

To set a value, you can use setValue() method directly on the reference like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users").child(user.getDisplayName());
userRef.child("deposit").setValue(9); //Sets the value to 9

To get the value, please use the following code:

ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int deposit = dataSnapshot.child("deposit").getValue(Integer.class);
        Log.d("TAG", deposit);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);

Please see the correct DatabaseReference which contains Users and not only User as shown in your screen-shot.

Upvotes: 1

AlexTa
AlexTa

Reputation: 5251

According your database structure the child you should reference is Users and in your code you are calling User. Fix that mistake...

//Replace child tag by Users to fix the error
database.child("Users").addValueEventListener(new ValueEventListener() { ...

Upvotes: 1

Related Questions