0

Here I am adding the snippet where I am successfully retrieve data from firebase and use it as in my textview inside onDataChange() function but when I try to use it outside this function then it's not working and also I dont want to bring TOOLBAR inside onDataChange Function cause I have other places too where I need to use the data.

            DatabaseReference databaseReference = firebaseDatabase.getReference(firebaseAuth.getUid());

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
            //profileName.setText(userProfile.getName());


                pasteName = userProfile.getName();
                pasteEmail = userProfile.getEmail();
                testCase.setText(pasteName);//THIS IS WORKING


        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(LoggedIn.this,"Problem Fetching Data",Toast.LENGTH_SHORT).show();
        }
    });


    toolbar = (Toolbar)findViewById(R.id.toolbarMain);
    toolbar.setTitle(pasteName);//NOT WORKING
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Faizan Khan
  • 89
  • 1
  • 2
  • Please check the duplicate to see why do you have this behaviour and how can you solve this using a custom callback. And as a quick fix, move the last two lines of code inside the callback. – Alex Mamo Mar 19 '19 at 08:52

1 Answers1

1

The problem you have is that the request is async, so pasteName = userProfile.getName(); is executed after the query finishes, so you have the info available.

toolbar = (Toolbar)findViewById(R.id.toolbarMain);

toolbar.setTitle(pasteName);//NOT WORKING

That won't work because that executes immediately after the query was executed, but it might have not finished.

Community
  • 1
  • 1
Juan Giorello
  • 333
  • 2
  • 13
  • Thanks.. But can it be rectified for the correct and desirable result ... ? – Faizan Khan Mar 19 '19 at 08:07
  • The correct way to do that is just as you did: put the code (or better, create a function) and call it from inside the onDataChange method. The key here is that the line with //NOT WORKING executes sync and the "pasteName" and "pasteEmail" variables have not been loaded yet (the request has not finished) – Juan Giorello Mar 22 '19 at 12:59