Gregory Zaika
Gregory Zaika

Reputation: 124

Getting an access to a variable after onDataChange has retrieved it

I have an application which, at one point, retrieves a variable from the Firebase Database using Query#addListenerForSingleValueEvent() method. The code is as follows:

void initCurrentUserProfile () {
    mAuth = FirebaseAuth.getInstance();
    mUser = mAuth.getCurrentUser();
    mFirebaseDatabase = FirebaseDatabase.getInstance();

    DatabaseReference userProfileReference =   mFirebaseDatabase.getReference().child("users");
    userProfileReference = userProfileReference.child(mUser.getUid());

    Query userProfileQuery = userProfileReference.orderByKey();
    userProfileQuery.addListenerForSingleValueEvent(new ValueEventListener() {


        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

        // This is the variable that I want to get
        mUserProfile = dataSnapshot.getValue(UserProfile.class);
        }
...

I want to get an access to mUserProfile, which is a class with the user data right away in the onCreate() of my activity and load the picture the URL of which is contained within this mUserProfile variable.

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    initCurrentUserProfile();
    Picasso.with(this).load(Uri.parse(mUserProfile.getProfilePicUrl())).into(mProfilePictureImageView);
}

The problem is, because of asynchronous nature of Firebase Database, I can't do it and get a NullPointerException:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.grigori.fitnessapp.Profile.UserProfile.getProfilePicUrl()' on a null object reference

Do you have any suggestions as to what I might do in order to get access to this variable?

Upvotes: 0

Views: 124

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 1

Yes, you need to call this line of code:

Picasso.with(this)
    .load(Uri.parse(mUserProfile.getProfilePicUrl()))
    .into(mProfilePictureImageView);

Right in the onDataChange() method and not in onCreate() method otherwise it will be always null.

The asynchronous behaviour means that the line above is called before you are trying to get the data from the database and that's why is always null.

Upvotes: 1

Related Questions