I have an arraylist inside another arraylist , when i enter values, value of the previous arraylist automatically changes to last entered value.
Code is as follows
Question.class
data class Question(
var id: String,
var question: String,
var correct: String,
var answer: ArrayList<String>
)
MainActivity
answers.add("1234")
answers.add("234")
questions.add(Question("1","1","1",answers))
Log.d("12345",questions.toString())
answers.clear()
answers.add("5678")
answers.add("789")
questions.add(Question("2","2","2",answers))
Log.d("12345",questions.toString())
o/p
D/12345: [Question(id=1, question=1, correct=1, answer=[1234, 234])]
D/12345: [Question(id=1, question=1, correct=1, answer=[5678, 789]), Question(id=2, question=2, correct=2, answer=[5678, 789])]
You only have one list of answers here. Each question gets a reference to that single list. Instead, you should create a new list of answers for each question. To understand this better, I suggest you read about references in Kotlin.
Related
I have a list that I want to sort. That list contains multiple maps with key and values.
Basically, it looks like this:
class MyObject{
DateTime date;
String myText;
MyObject({required this.date, required this.myText});
}
void main()
{
MyObject obj1 = MyObject(date: DateTime.now(), myText: "abc");
MyObject obj2 = MyObject(date: DateTime.now(), myText: "bcd");
// just a demo, in reality there are more unordered dates
var myList = [{"obj": obj1 , "etc": "someEntry1"}, {"obj": obj2, "etc": "someEntry2"}];
}
I want to sort the list based on ascending dates in the maps and tried the following line of code to sort the list:
myList.sort((a, b) => a['obj'].date.compareTo(b['obj'].date));
But I ended up getting the following error:
How to solve the sorting problem?
Thanks for your help!
I couldn't replicate the exact same error. But you can make it sort, as I think you want, by making a small adjustment.
Since your map is mixing datatypes, then you have to help dart know that the object under the key "obj" is of type MyObject. Check this DartPad where I've added a cast.
This is what I've changed:
myList.sort((a, b) => (a['obj']! as MyObject).date.compareTo((b['obj']! as MyObject).date));
Note that you might want to do something safer than just assuming that x['obj'] will not be null...
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
Firestore Database Accessing Code in Activitymain.xml
db.collection("billNo") // I think want to add some code here to get the data!!//
.get()
.addOnSuccessListener {
user.clear()
for (document in it) {
user.add(User(
document.id,
document.data.get("billNo").toString().toInt(),
document.data.get("date").toString(),
document.data.get("name").toString(),
document.data.get("amount").toString().toInt(),
document.data.get("payment").toString()
)
)
}
Database Structure
#Parcelize
data class User(
val id: String,
val billNo: Int,
val date: String,
val name: String,
val amount: Int,
var payment:String
) : Parcelable
I Add billNo, date, name, amount, paid_or_unpaid data into the FIREBASE DATABASE. So when I click on searching I want to get details of the selected month in the RecyclerView. All RecyclerView code and other things working perfectly fine. Only I want to retrieve the data of the selected month.
When I click on the Respective Month & Year in the Following Activity (Screenshot is provided below) I want to get the details of bills in the respective month from the FIREBASE FIRE STORE DATA Base. I tried a lot. but I can't find a solution. I'm doing my project on Android Studio with KOTLIN programming Language.
There is no LIKE operator in Firestore. So a query like this:
"SELECT * from tablename WHERE date LIKE %$month-$year%"
Is actually not possible. Because your "date" field is actually a String, when using small data sets you might consider using:
Is there a way to search sub string at Firestore?
Or you can try using the newly Firebase Extension announced at Google I/O 2021 called:
Search with Algolia
Or directly in code:
Is it possible to use Algolia query in FirestoreRecyclerOptions?
However, there are two workarounds that can be used to achieve the same result. The first one would be to create another field in your User object called "monthYear". This property will hold a different value than the "date" property. For instance, if your "date" property holds the value of "03-May-2021", "monthYear" property will only hold the value of "May-2021". That been said, the Query will look like this in Kotlin:
val rootRef = FirebaseFirestore.getInstance()
val queryByMonthYear = rootRef.collection("billNo").whereEqualTo("monthYear", "May-2021")
The second solution would be to change the type of the "date" from String to Timestamp. Please see below how you can add a Timestamp to Firestore:
How to add a Timestamp in Firestore with Android?
It's in Java but you can simply convert it in Kotlin. Then, you can use a Query with a call to startAt(startDate) and endAt(endDate).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to read nested array and maps in android studio (Java) from firestore but could not able to iterate through it. I am new to it so can anyone please help me. Thank you :)
Edited: How can I iterate through "options" as it is an array in map.
I've achieved the rest by saving them in HashMap and iterating through it.
First, make a data class for your JSON. You can do it with this plugin
Let's say you have something like that (this example done in kotlin):
data class Data(
val id: Int,
val lists: List<Company>,
val name: String
)
data class Company(
val q: String,
val type: String,
val optType: Int?,
val data: List<Options>?
)
data class Options(
val option : String
)
After that, you can do a loop following
for (Company list : data.getLists()) { // data is your object. GetList returns first array
for (Options datum : list.getData()) { // from list you will get next array.
System.out.println(datum.getOption()); // here you will get item from nested 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