Issue
I am currently trying to read data from Cloud Firestore, but while doing this I get this error message:
For-loop range must have an 'iterator()' method
And I don't know what to do to get rid of it. Maybe there is an easy way to fix this I haven't thought of yet... I have been using this google firebase tutorial but with no success.
The error message comes on the documents
in the for (document in documents)
part of the code
The code I am using is this:
`
fun Varer() {
var firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
var docRef = firestore.collection("varer").document("varer")
var source = Source.DEFAULT
docRef.get(source).addOnSuccessListener { documents ->
for (document in documents) {
Log.d(TAG, "${document.id} => ${document.data}")
var v1 = VareFB(
tittel = document["tittel"].toString(),
pris = document.getDouble("pris"),
beskrivelse = document["beskrivelse"].toString(),
bildeID = document["bildeID"].toString(),
)
varerListe.add(v1)
Log.d(TAG, document["tittel"].toString())
Log.d(TAG, v1.toString())
}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Feil med henting av varer: ", exception)
}
}
`
data class VareFB (
val tittel: String,
val pris: Double?,
val beskrivelse: String,
val bildeID: String,
) {
@Exclude
fun toMap(): Map<String, Any?> {
return mapOf(
"tittel" to tittel,
"pris" to pris,
"beskrivelse" to beskrivelse,
"bildeID" to bildeID,
)
}
}
`
object VarerObject {
var varerListe = mutableListOf<VareFB>()
}
`
Edit:
fun Varer() {
var firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
var docRef = firestore.collection("varer").document("varer")
var source = Source.DEFAULT
docRef.get(source).addOnSuccessListener { snapshot ->
for (document in snapshot.documents) {
Log.d(TAG, "${document.id} => ${document.data}")
var v1 = VareFB(
tittel = document["tittel"].toString(),
pris = document.getDouble("pris"),
beskrivelse = document["beskrivelse"].toString(),
bildeID = document["bildeID"].toString(),
)
varerListe.add(v1)
Log.d(TAG, document["tittel"].toString())
Log.d(TAG, v1.toString())
}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Feil med henting av varer: ", exception)
}
}
Solution
documents
is a QuerySnapshot object so there is no way you can iterate over it. To be able to iterate through the documents, you have to get the documents out of the QuerySnapshot object like this:
firestore.collection("varer").get(source).addOnSuccessListener { documents ->
for (document in documents.documents) {
//
}
}
But in my opinion, it's a little confusing. So I would rather name the object that comes from the lambda expression snapshot
:
// 👇
firestore.collection("varer").get(source).addOnSuccessListener { snapshot ->
for (document in snapshot.documents) {
// 👆
}
}
Answered By - Alex Mamo
Answer Checked By - Senaida (JavaFixing Volunteer)