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
Related
I have tried to decode a json file which is coming back from server after my request, but when i want to decode the json it show an error
here is my decode codes:
var loginJson = jsonDecode(utf8.decode(response.bodyBytes));
var model = idResponseModel(
loginJson['id'],
loginJson["fname"],
loginJson["lname"],
loginJson["nationalCode"],
loginJson["gender"],
loginJson["bornDate"],
loginJson["phoneNumber"],
loginJson["cardNumber"],
loginJson["enabled"]);
print(model.id);
and console says it happened in loginJson['id']
the id from server is some thing like this :
"id": "5de0a41e-9a6f-4b55-9567-024cd0fdbfc5"
slightly surprised by the direct use of [bodyBytes] try using the Response getter → body
String get body => _encodingForHeaders(headers).decode(bodyBytes);
in your case it should look like this:
var loginJson = jsonDecode(response.body);
var model = idResponseModel(
loginJson['id'],
loginJson["fname"],
loginJson["lname"],
loginJson["nationalCode"],
loginJson["gender"],
loginJson["bornDate"],
loginJson["phoneNumber"],
loginJson["cardNumber"],
loginJson["enabled"]);
print(model.id);
I have no way to check it now but if it works let me know
This error means that loginJson.[] expects an int, not a String. So it's possible that loginJson is actually a List, and not a Map like you expect it to be. You can check by printing loginJson.runtimeType.
Unless you'd post the whole JSON, this question is insufficient and not reproducible... because you might believe you have the response already, while trying to get data from the wrong one node (id is a string index, but it encounters an unexpected numeric index). That's exactly why your sample data and the error message do not provide the least meaning in combination.
I want to keep a list with the ID of the users who liked the specific object. To achieve that I created an array where I'm trying to keep that list.
I also want to display how many users like that object.
In mapper:
likes = getLikedListSize(it["userLikedOfferList"].toString())
then
private fun getLikedListSize(userList: String): String {
return userList.length.toString()
}
The problem is that function returns random numbers. For example in the array are two items, function return "8" etc.
What is a better approach to store list and get the size of it in Firestore?
When you are using the following method call:
getLikedListSize(it["userLikedOfferList"].toString())
It means that you are trying to pass to the getLikedListSize() method, the String representation of the array object. This representation is nothing else but the address of the object in the memory. This address it's a String that consists of 8 characters. That's the reason why, when you call .length you return the length of that String and not the actual length of the array. To solve this, simply pass the array, without converting it to a String:
getLikedListSize(it["userLikedOfferList"])
And change the method like this:
private fun getLikedListSize(userList: Array<String>): Int {
return userList.length
}
Now, when calling this method, you'll always get the number of elements that exist in the userLikedOfferList array.
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
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.
I have the following array response from a server to an android app.
[
{"1":
[{"name":"IEEE Meeting"},{"date":"2012-04-24 10:30:00"},{"Room":"ZACH102"},{"descr":"Final Meeting"},{"D":0.0057}]},
{"2":
[{"name":"Senior Design Demo"},{"date":"2012-04-24 16:30:00"},{"Room":"ZACH111A"},{"descr":"Demo"},{"D":0.019}]}
]
I perform a conversion to a JSONArray after receiving the response.
arr = new JSONArray(sb.toString());
How would I go about extracting the individual elements of name, date, room and so on?
So basically, its of this order
Array of objects 1, 2
- Each object 1, 2 has an array of different objects name, date, etc.
Convert the whole data in to a string.
Create a new JSONArray(string).
Loop over the array. (you'll get the count using length()).
Get the first object by using getJSONObject().
Get the array in the first object using getJSONArray.
Now using length() again you'll get the number of JSONObjects in it.
Loop over the num of objects and call get JSONObject() first followed by getString() or getDouble().
Repeat over the list of other objects and repeat step 4 - 7.
Have you checked out the documentation for JSONArray?
From the documentation, the internal form is an object having get and opt methods for accessing the values by index, and put methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object.
A get method returns a value if one can be found, and throws an exception if one cannot be found. An opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional values.
The generic get() and opt() methods return an object which you can cast or query for type. There are also typed get and opt methods that do type checking and type coercion for you.
you can get all the parameters like this
JSONArray main_array = json.getJSONArray("array");
for(int i=0;i<main_array.length();i++) {
main_object = main_array.getJSONObject(i);
String name = main_object.getString("name");
String date = main_object.getString("date");
}