skip to Main Content

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?

2

Answers


  1. 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())
            }
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search