I want to add colection to Firestore database like this image:
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?
2
Answers
The issue is that every time you call the
addsymbol
function, you are creating a new instance of thearrayList
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:
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:
I also recommend attaching a complete listener, to see if something goes wrong.