How to read array data from the firestore using kotlin? - android

I am new in android development and when I read array data from firestore using following code
val variable = arrayOf(document.get("restaurant"))
and then loop over the variable using code
varibale.forEach {
Log.d("someTag", ${it.toString()} + " is your data")
}
I get the result with square brackets at log as following
[somedata, somedata2] is your data
my problem is that forEach loop runs only once and I am not able to get the result (without square brackets) as following
somedata is your data
somedata2 is your data
I have 2 elements in my restaurant array in firestore
I will be very thankfull to any one who will help me.

You are actually wrapping an array/list into another array when using arrayOf, that's why you see those brackets. Instead, try casting your document.get("restaurant") and then looping directly through it.

arrayOf doesn't parse an array. It creates a new array using the elements you pass to it. That's not what you want. You should instead cast document.get("restaurant") to the type that you expect to get from Firestore.
If a field is an array of strings, then the SDK will give you a List<*>, and you will need to make sure each item in the list is a String, if that's what you stored in the array.
val variable = document.get("restaurant") as List<*>
// Iterate variable here, make sure to check or convert items to strings

Related

Failing to Update Array in Firestore

I am trying to update Array in Firestore. From what I know you cant just append to the array in Firestore instead you need to replace the complete array with a new one.
Following is the code in Kotlin where I was trying to update the array:
holder.button.setOnClickListener {
pending.add(o[0])
Firebase.firestore.collection("profiles").document("YHMauLouORRtrYBV2h4dHJ5A0s72").update(
"Pending" , "$pending"
)
Here o[0] is the string I desire to Append to the already Existing Array named pending
Initialy in Firestore :-
Output I am getting :-
Output I desire:-
Basically While updating its converting the Array to a sting of list and pushing to Firestore. How can I get the Desired Output as shown in image ?
Thanks in Advance
That's not how to update an array in Firestore. To achieve that, you should use:
Firebase.firestore.collection("profiles")
.document("YHMauLouORRtrYBV2h4dHJ5A0s72")
.update("Pending", FieldValue.arrayUnion("Banana"))
When you're calling update without the second argument it means that you want to update a regular field.

Kotlin Firebase get specific data from field

I have a problem because I want to get every languages1 from all Decks. I cannot get there. I tried like this:
document.data["languages"][1] <--- error
Only works this:
document.data["languages"]
But this above returns me all languages, but I want to get only second language from the array and do distinct from this list. How to get this? Now my code looks like this:
val documents = db.collection("Decks")
.get()
.await()
val languages = documents?.mapNotNull { document ->
document.data["languages"] as String
}
Any tips?
Here is how looks my database:
This is not how to deal with that type of field:
document.data["languages"][1]
DocumentSnapshot#getData() method, returns an object of type Map<String, Any>. When you try to read the value that corresponds to a specific key, you actually don't know what kind of object is returned. It can be an array or any other object that is one of the supported data types. Seeing your document, the "languages" field is indeed an array, so you need to cast the object to a List. In order to get the second element, please use the following line of code:
val en = (document.data["languages"] as List<String>)[1]
If you try to log this value, you'll get as result:
en

How to append an array into an array field in firestore?

Question
I have a collection named Users with a field named friendEmails which is an array that contains Strings.
I have a document with friendEmails = {joe#gmail.com, dan#gmail.com}, and I want to append newEmails = {mat#gmail.com, sharon#gmail.com} to it.
Problem
The only options I know for this are:
Reading the friendEmails array first, then adding the union of it and newEmails to the document.
Iterating over the elements of newEmails (let's and each iteration doing:
myCurrentDocumentReference.update(FieldValue.arrayUnion, singleStringElement);
(Since FieldValue.arrayUnion only lets me pass comma-separated elements, and all I have is an array of elements).
These two options aren't good since the first requires an unnecessary read operation (unnecessary since FireStore seems to "know" how to append items to arrays), and the second requires many write operations.
The solution I'm looking for
I'd expect Firestore to give me the option to append an entire array, and not just single elements.
Something like this:
ArrayList<String> newEmails = Arrays.asList("mat#gmail.com", "sharon#gmail.com");
void appendNewArray() {
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
firestore.collection("Users").document("userID").update("friendEmails", FieldValue.arrayUnion(newEmails));
}
Am I missing something? Wouldn't this be a sensible operation to expect?
How else could I go about performing this action, without all the unnecessary read/write operations?
Thanks!
You can add multiple items to an array field like this using FieldValue.arrayUnion() as the value of a field update:
docRef.update("friendEmails", FieldValue.arrayUnion(email1, email2));
If you need to convert an ArrayList to an array for use with varargs arguments:
docRef.update("friendEmails", FieldValue.arrayUnion(
newEmails.toArray(new String[newEmails.size()])
));

Make Score History in Array Field Firestore

How to make history score in Array
I try u make score in array like this
this my firestore
And this is my code
String uid = auth.getCurrentUser().getUid();
muridref.document(uid).update("nilai", FieldValue.arrayUnion(skortampil));
When I get the same score the array field doesn't make new Array data,
without see data there or not in array
As mentioned in the documentation Update elements in an array about this behavior:
If your document contains an array field, you can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present.
Considering that, it's working as expected, since it's not adding values that are equal. So, this means that you won't be able to add values that are equal using the method arrayUnion() directly.
This other question from the Community - accessible here - indicates that for you to achieve this goal, you will need to read all the values from the array in your client side, update your values in the array outside the database and then, writing/updating it back in the database.
Let me know if the information helped you!

get / fetch data from boolean array - Firestore Android

firestoredatabase
Hi! i want to get data from an array of boolean from my firestore data base, if i run this code:
Log.d("firestore", String.valueOf(document.getData()));
I get this result:
{nombre=AVL, boolArray=[true, false, false]}
document.get("boolArray") should return a List<Boolean> type object.
document.getData() will return a Map which in term contains two other maps. In the first case, the value is of type String while in the second case, the value is an Array. But if you are using document.get("boolArray"), as Doug said, even if we know that data is stored as an array, the data is returned as a List<Boolean>.
If you want to read more, you can also see my answer from this post.

Categories

Resources