Android: How to write array list of strings in Firestore

Viewed 3299

I need to write a simple collection where documents only contain an array list of strings.

usersBlocked
    -blockerID
         - usersBlockedList
               -userID1
               -....
               -userIDN

At this moment I'm able to update the list if the document already exist in this way: (for testing porpouses I wrote it by hand).

val reference = Firebase.firestore
            .collection("usersBlocked")
            .document(userIDBlocker)

reference.update("usersBlocked", FieldValue.arrayUnion(userIDToBlock))
            .addOnSuccessListener { Logger.d("Blocked") }
            .addOnFailureListener { Logger.d(it.localizedMessage) }

As I said, if the document exists, the update is correct, but when there is no document... I'm getting this error:

NOT_FOUND: No document to update: projects/xxxxxx/databases/(default)/documents/usersBlocked/2oLOYbG2z9gRC5VugchEP7ZPpy53

I assume that obviously not exist, but I don't know how to write Arrays in a document.

I saw how to save Maps, but is not what I need.

DB Structure:

enter image description here

2 Answers

First you have to confirm that there is any document available with your current userid. Put condition like i have put. It will check whether id is available or not. If id is not available. Then it will generate new document at your usersBlocked with uid and store array.

val reference = Firebase.firestore
    .collection("usersBlocked")
    .document(userIDBlocker).get()
        .addOnSuccessListener { documentSnapshot ->
            if (documentSnapshot.exists()) {
                reference.update("usersBlocked", FieldValue.arrayUnion(userIDToBlock))
            } else {
                val userdetail = HashMap<String, Any>()
                var usersBlockedList = arrayListOf<String>()
                usersBlockedList.add(userIDToBlock)
                userdetail["usersBlocked"] = usersBlockedList
                Firebase.firestore.collection("usersBlocked").document(userIDBlocker).set(userdetail)
                        .addOnSuccessListener { success ->

                        }
                        .addOnFailureListener { exception ->
                            Log.e("Data Failed", "To added because ${exception}")
                        }

            }
        }
        .addOnFailureListener { exception ->
        Log.e("Exception", "${exception}")
        }
Related