0

Why does my variable not get updated after the onComplete method has finished?

I have a public int variable 'numPoints'. When I call a method 'CalculateBatPoints' I update the variable numPoints inside of a onComplete method. However, when the onComplete method is complete, the numPoints value doesn't appear to have been updated.

private void CalculateBatPoints(ArrayList<String> listBat){
        numPoints = 0;
        for (int i=0;i<listBat.size();i++){

            db.collection("players").document(listBat.get(i)).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    DocumentSnapshot ds = task.getResult();
                    numPoints = Integer.parseInt(ds.getString("gwPoints")) + numPoints;
                    System.out.println(numPoints);
                }
            });
        }
        System.out.println("numPoints is " + numPoints);
    }

The output I got was: 32 158 185 271 numPoints is 0

I expected the output: 32 158 185 271 numPoints is 271

coderMani
  • 13
  • 2
  • If you check the order of the log output, you'll see that the variable *does* get updated, but only after your `System.out.println("numPoints is " + numPoints)` has already executed. That's because data is loaded from Firestore (and pretty much any cloud API) asynchronously. I linked a few questions explaining this in more detail. – Frank van Puffelen Jan 28 '23 at 17:40
  • Is there anyway around this? – coderMani Jan 28 '23 at 18:46
  • Yes, as shown in the links I provided: any code that needs the data from the database will have to be inside the `onComplete`, be called from there, or otherwise synchronized. – Frank van Puffelen Jan 29 '23 at 06:44
  • I think you might also be interested in reading this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-cloud-firestore-using-get-bf03b6ee4953). – Alex Mamo Jan 31 '23 at 06:54

0 Answers0