1

Can i get a specific data from firebase database without calling the addValueEventListener. In my code i'm successfully getting the data using firebase database but when i use a function that contains the addValueListener and call the function i can't get the data. Here is my code:

 for(CheckOut g: GroceryActivity.list){

        String pid = g.getPid();
        Log.i("PID", pid);
        getOriginalQuantity(pid);
        Log.i("Original_Quantity", "" + originalQuantity);}

 public void getOriginalQuantity(String pid){

    originalQuantityReference = originalQuantityReference.child(pid);

    originalQuantityReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Grocery grocery = dataSnapshot.getValue(Grocery.class);
            originalQuantity = grocery.getQuantity().toString();
            Log.i("Original Quantity", originalQuantity);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}//end getOriginalQuantity method

I'm getting the correct data from the log in the addValueListener where in the the other log i'm getting null valeu

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
saad bitar
  • 45
  • 1
  • 6
  • 1
    As others have said: the Firebase API (like most of the modern Cloud APIs) is asynchronous. The only way to use it synchronously would be to call its HTTPS REST API, but I **highly** recommend against that. The best you can do is get to grips with asynchronous programming. This will take time, but will give you the best results, and your user's the best apps. For a longer explanation, see my answer here: https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Mar 28 '20 at 15:11

2 Answers2

4

Firebase api is asynchronous meaning that when you use AddValueEventListener to retrieve data from the database, the program will not stop and continue executing. Therefore in this log:

Log.i("Original_Quantity", ""+originalQuantity);

You will get null since it is executed before the data is fully retrieved. There are two ways to access the data either inside the onDataChange or you can do the following:

How to return DataSnapshot value as a result of a method?

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
2

No, to get specific data from firebase database you must use addValueEventListener or addListenerForSingleValueEvent