I’m trying to create an application that can read the values from a Firestore array and put them into an ArrayList or something, this is my code:
ArrayList<Integer> driverPermissions = new ArrayList<>();
Firestore.collection("Admins").document("1234567890").get().addOnCompleteListener(task -> {
DocumentSnapshot document = task.getResult();
driverPermissions = document.get("Test");
});
Unfortunately, it doesn’t work. It marks me as an error in this line:
driverPermissions = document.get("Test");
And the error is:
Variable used in lambda expression should be final or effectively final
How can I add the values present inside the array on Firestore into an ArrayList or something like that and then use that throughout the code? And not only within the method?
3
Answers
Try This
Your trying to get data type String but You declared Array tn Integer first mistake.
Then try this
Here you can store only store string type data.
Or you can try like this
Here you can store any kind of data can be integer can be string But You have to declared what kind of data your storing.
On Demand Way
Another way
A variable that is used in a lambda expression should always be final or effectively final, and you cannot change that. To solve this, you either make the variable a member of the class or define it and initialize it inside the
onComplete()
.There is no way you can do that. Firebase API is asynchronous, meaning that any code that needs data from Cloud Firestore, needs to be inside the
onComplete()
method, or be called from there. You cannot simply use it outside the callback, even if the field is a member of the class. So to solve this you can use a custom callback as seen in that answer. The reason is that you need to wait for the data. If you understand Kotlin, you might also be interested in reading the following resource:In Java, you should consider using LiveData. I think this repo might also help.
P.S. If you need at some point in time to use an array of objects, here is another helpful resoruce: