1

I'm writing an android app, where I need to read some data from the firebase database. First I was doing it in the mainActivity.java class, but than it started looking messy. So, I made a new class, that would manage all the database related things. But for some reason I can't use the data I'm getting, outside of the ValueEventListener method.

Below you can see my code. I hope I was clear enough about my problem. I would be very grateful if somebody would like to help. Thanks!

public class UserManager {
    public Long getUserScore() {
    final Long[] score = new Long[1];
    DatabaseReference databaseReferenceUser;
    databaseReferenceUser = FirebaseDatabase.getInstance().getReference("users");
    databaseReferenceUser.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                User user = dataSnapshot.getValue(User.class);
                score[0] = user.getScore();
                Log.w("Score: ", score[0].toString()); // output: value from the db- Works fine

            }
            Log.w("Score: ", score[0].toString()); // output: value from the db- Works fine
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
    Log.w("Score: ", score[0].toString()); // output: NullPointerException
    return score[0];
}}
Nida Ilyas
  • 71
  • 5

0 Answers0