Getting one value of a map in Firestore in Kotlin - android

I have a document with this structure in Firestore:
Where queue is a map. I want to get the value of the key active inside
val restaurantRef = db.collection("restaurants")
restaurantRef
.get()
.addOnSuccessListener { result ->
var queueStatus = ArrayList<Boolean>()
for (document in result) {
queueStatus.add( ... ) // How do I get the active value in my map here?
}
}
How do I get the value of active inside my queue map?

I've figured out the answer. On the queueStatus.add(...) line, replace it to these lines:
val docMap = document.get("queue") as Map<String, *>
queueStatus.add(docMap.get("active") as Boolean)

Related

How can I add colection to Firestore Database as in image?

I want to add colection to Firestore database like this image:
here
I want to add a symbol in Arraylist every time the function is called.
fun addsymbol(){
val arrayList= arrayListOf<String>()
arrayList.add(Coin.Coin_Info?.symbol!!)
val postHashMap = hashMapOf<String, Any>()
postHashMap.put("symbols",arrayList)
Firestore.collection("Users").document("User1").set(postHashMap, SetOptions.merge())
.addOnCompleteListener { task->
if(task.isSuccessful){
System.out.println("Succes ")
}
}.addOnFailureListener {
System.out.println( it.message.toString())
}
}
Function working but It's not adding symbols to arraylist , It's updating arraylist . How can I solve it?
There is no need to read the array in the document in order to add a new symbol. You can simply pass FieldValue#arrayUnion() as an argument to the update method like this:
Firestore.collection("Users").document("User1").update("symbols", FieldValue.arrayUnion(Coin.Coin_Info?.symbol!!))
I also recommend attaching a complete listener, to see if something goes wrong.
The issue is that every time you call the addsymbol function, you are creating a new instance of the arrayList and then adding a symbol to it. However, you are not retrieving the existing array of symbols from the Firestore database and appending the new symbol to it. To fix this, you need to retrieve the existing array of symbols, append the new symbol to it, and then update the Firestore database with the new array.
try the following:
fun addsymbol(){
Firestore.collection("User").document("Userid").get()
.addOnSuccessListener { documentSnapshot ->
if (documentSnapshot.exists()) {
val symbols = documentSnapshot.get("symbols") as ArrayList<String>
symbols.add(Coin.Coin_Info?.symbol!!)
val postHashMap = hashMapOf<String, Any>()
postHashMap.put("symbols", symbols)
Firestore.collection("User").document("Userid").set(postHashMap, SetOptions.merge())
.addOnCompleteListener { task ->
if (task.isSuccessful) {
System.out.println("Success")
}
}.addOnFailureListener {
System.out.println(it.message.toString())
}
} else {
System.out.println("Document does not exist")
}
}
.addOnFailureListener {
System.out.println(it.message.toString())
}
}

How to read documents from Firestore that was added using hashMap in Kotlin?

I have managed to add data as hashMap into Firestore as follows but I have a hard time reading all documents from Firebase without a model class.
val itemRequest = hashMapOf(
"item" to newItem,
"item_detail" to itemDetails,
"requested_by" to getCurrentUserID(),
"timestamp" to FieldValue.serverTimestamp(),
)
mFireStore.collection("item_request")
.document()
.set(itemRequest)
.addOnSuccessListener {
fragment.successAddingItemRequest()
}
.addOnFailureListener {
}
You can use DocumentSnapshot.data property to convert the DocumentSnapshot to Map<String, Any>.
In your case, you can use:
firestore.collection(collectionId).document(documentId).get()
.addOnSuccessListener { documentSnapshot ->
val data = documentSnapshot.data
val item = data["item"]
val itemDetails = data["item_detail"]
...
}
Here you will have to cast the returned Any map value to its appropriate data type.
But a better way to do all this would have been to create a model class for storing data and using DocumentSnapshot.getObject to get the data back.

Get data from Firestore where an array match a list of data in Kotlin

Following is the structure of my Firestore database. I want to get all the documents from the collection 'products' where the 'pin_code' (is an Array) matches with the list of pin codes I have. The list of pin codes is from the collection 'addresses' which I have managed to get with the following code. But I am not able to get documents from the collection 'products' that match the list of pin codes.
Following is the code I have to get the pin code list from the collection 'addresses'
fun getPins(context: DashboardFragment) {
mFireStore.collection("addresses")
.whereEqualTo("user_id", getCurrentUserID())
.get()
.addOnSuccessListener { document ->
val codeList: MutableList<String> = mutableListOf()
for (i in document.documents) {
val code = i.toObject(Address::class.java)
code!!.user_id = i.id
codeList.add(code.pinCode)
}
context.getProductListBasedOnPin(codeList)
}
.addOnFailureListener { e ->
}
}
I tried to get the data from the collection 'products' with the following code. But with this code I can get the list of products only when my 'pin_code' is not an array. But I had to make the pin_code an array for some reason and I am not able to get the product list.
fun getProductListBasedOnPin(pinList: List<String>?) {
val mFireStore = FirebaseFirestore.getInstance()
mFireStore.collection("products")
.whereIn("pin_code", pinList!!)
.get()
.addOnSuccessListener { document ->
for (i in document.documents) {
val product = i.toObject(Product::class.java)!!
product.product_id = i.id
srchProductsList.add(product)
}
srchTempProductsList.addAll(srchProductsList)
if (newView == "ListView") {
successDashboardItemsListListView(srchTempProductsList)
} else {
successDashboardItemsList(srchTempProductsList)
}
}
.addOnFailureListener {
}
}
Can someone help me with this?
Thank you.
I want to get all the documents from the collection 'products' where the 'pin_code' (is an Array) matches with the list of pin codes I have.
You can definitely do that using Query's whereArrayContainsAny(String field, List<? extends Object> values) method, which:
Creates and returns a new Query with the additional filter that documents must contain the specified field, the value must be an array, and that the array must contain at least one value from the provided list.
Assuming that you want to get all documents from the "products" collection in which the "pin_code" arrays contains a List with two values ("123456" and "159874"), please use the following lines of code:
val pinCodeList = listOf("123456", "159874")
productsRef.whereArrayContainsAny("pin_code", pinCodeList).get().addOnCompleteListener {
if (it.isSuccessful) {
for (document in it.result) {
Log.d(TAG, document.id + " => " + document.data)
}
} else {
Log.d(TAG, "Error getting documents: ", task.exception)
}
}
This is done using an Array Contains conditions, using one of the various methods, you can see if an array contains some, any, all, and not-in.
val citiesRef = db.collection("products")
citiesRef.whereIn("pin_code", listOf("123456", "150875"))
Once you fetch this snapshot, it will return an array of matching documents which you can then use with other sections of your app logic and secondary Firestore queries as needed.
Source: https://firebase.google.com/docs/firestore/query-data/queries#kotlin+ktx_6

Firebase Cloud Firestore does not return data or errors

I am learning to use Firebase Firestore and I have created a list of items that I want to display in my app. When trying to load the list, I don't receive the data but I also don't get any error. I cannot display the data in the Log. What could be happening?
fun getDriverData(): LiveData<MutableList<Driver>> {
val mutableData = MutableLiveData<MutableList<Driver>>()
FirebaseFirestore.getInstance().collection("drivers").get().addOnSuccessListener { result ->
val listData = mutableListOf<Driver>()
Log.i("repo","called")
for (document in result) {
val photoUrl = document.getString("photoUrl")!!
val name = document.getString("name")!!
val team = document.getString("team")!!
Log.i("repo", "${document.id}} => ${document.data}")
val driver = Driver(name,team,photoUrl)
listData.add(driver)
}
mutableData.value = listData
}.addOnFailureListener {
Log.i("repo", "getDriverData: ${it.message}")
}
return mutableData
}
Your collection is actually called "drivers" - WITH the quotation marks. Whatever is generating the documents here is using extra quota when building the name of the collection.
You could read them back by adding those quotes:
FirebaseFirestore.getInstance().collection("\"drivers\"").get()
But you probably want to fix the code that generates the document to not add those quotes.

Kotlin not able to query users collection

I'm trying to run a query in Firebase to get the value of an specific field in the USERS collection and I don't understand why .documents it's an Unresolved Reference. Any ideas?
fun getUserSpecialty() {
val user = FirebaseAuth.getInstance().currentUser!!.uid
val specRef = usersCollectionRef.document(user)
specRef.get().addOnSuccessListener { snapshot ->
for (document in snapshot.documents) { //.documents it's an Unresolved Reference
val data = document.data
val userSpecialtyCode = data!![SPECIALTY_CODE] as String
val loggedUserSpecialty = UserSpecialty(userSpecialtyCode)
userSpecClass.add(loggedUserSpecialty)
this.userSpecTxt?.text = userSpecialtyCode
}
}
}
It's because snapshot is a DocumentSnapshot, and as you can see from the linked API documentation, it doesn't have a method called getDocuments() on it.
When you call get() on a DocumentReference as you are now, you get a single document as a DocumentSnapshot. You do not get a QuerySnapshot like you do with queries that could return multiple documents. You are probably confusing the two.

Categories

Resources