Home > OS >  Why is the .update("field","value") not working?
Why is the .update("field","value") not working?

Time:01-13

If you see the read messages function in my activity class below, i wanted to update the isSeen field in firestore, but for some reason it does not work at all. My guess it requires a specific document value but that would not be possible as this a messaging app so there will be a lot of documents created.

Activity Class

class MessageActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMessageBinding
    private lateinit var chat: ArrayList<Message>
    private lateinit var messageAdapter: MessageAdapter
    private lateinit var roomID: String
    private lateinit var userID: String
    private lateinit var recID: String
    private var c: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMessageBinding.inflate(layoutInflater)
        setContentView(binding.root)
        userID = FirebaseAuth.getInstance().uid.toString()
        recID = intent.getStringExtra("userID").toString()
        val recName:String = intent.getStringExtra("userName").toString()
        binding.userName.text = recName
        chat = arrayListOf()
        messageAdapter = MessageAdapter(chat)
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        when {
            userID < recID ->
            {
                roomID = userID   recID
            }
            userID.compareTo(recID) == 0 ->
            {
                Toast.makeText(this, "Error you are chatting with yourself!!!", Toast.LENGTH_SHORT).show()
            }
            else -> {
                roomID = recID   userID
            }
        }
        readMessages(userID,recID)
        binding.btnSend.setOnClickListener {
            val message: String = binding.textSend.text.toString()
            if(message.isNotEmpty()){
                sendMessage(userID,recID,message)
                binding.textSend.text.clear()
            }
            else{
                Toast.makeText(this,"You can't send empty message", Toast.LENGTH_SHORT).show()
            }
        }
        binding.gps.setOnClickListener {
            val uri = "http://maps.google.com/maps?daddr="
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri))
            intent.setPackage("com.google.android.apps.maps")
            startActivity(intent)
        }
    }

    private fun sendMessage(sender: String, rec: String, message: String){
        val db = Firebase.firestore
        val time: FieldValue = FieldValue.serverTimestamp()
        val msg = hashMapOf(
            "userID" to sender,
            "recID" to rec,
            "message" to message,
            "time" to time,
            "roomID" to roomID,
            "isSeen" to false
        )
        db.collection("chats").document(roomID).collection("messages").document().set(msg,SetOptions.merge())
    }
    private fun readMessages(userId: String, recId: String){
        val rootRef = Firebase.firestore
        rootRef.collection("chats").document(roomID).collection("messages").orderBy("time", Query.Direction.ASCENDING).addSnapshotListener(object : EventListener<QuerySnapshot?>
        {
            override fun onEvent(@Nullable documentSnapshots: QuerySnapshot?, @Nullable e: FirebaseFirestoreException?)
            {
                if (e != null)
                {
                    Log.e(TAG, "onEvent: Listen failed.", e)
                    return
                }
                chat.clear()
                if (documentSnapshots != null)
                {
                    for (queryDocumentSnapshots in documentSnapshots)
                    {
                        val msg = queryDocumentSnapshots.toObject(Message::class.java)
                        if (msg.recID == recId && msg.userID == userId || msg.recID == userId && msg.userID == recId)
                        {
                            chat.add(msg)
                        }
                        if(msg.recID.equals(userID).and(msg.userID.equals(recID))){
                            rootRef.collection("chats").document(roomID).collection("messages").document().update("isSeen",true)
                        }
                        messageAdapter = MessageAdapter(chat)
                        binding.recyclerView.adapter = messageAdapter
                    }
                }
            }
        })
    }
}

Adapter Class

class MessageAdapter(private val MessageList:ArrayList<Message>):RecyclerView.Adapter<MessageAdapter.MessageViewHolder>() {

    private val left = 0
    private val right = 1

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder {
        return if(viewType==right){
            val view1 = LayoutInflater.from(parent.context).inflate(R.layout.chat_sender_item,parent,false)
            MessageViewHolder(view1)
        }else{
            val view2 = LayoutInflater.from(parent.context).inflate(R.layout.chat_receiver_item,parent,false)
            MessageViewHolder(view2)
        }
    }

    override fun onBindViewHolder(holder: MessageViewHolder, position: Int) {
        val message:Message = MessageList[position]
        holder.showMessage.text = message.message
        if(position==MessageList.size-1){
            if(message.isSeen)
            {
                holder.textSeen.text = "Seen"
            }else{
                holder.textSeen.text = "Delivered"
            }
        }else{
            holder.textSeen.visibility = View.GONE
        }
    }

    override fun getItemCount(): Int {
        return MessageList.size
    }

    class MessageViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView){
        val showMessage: TextView = itemView.findViewById(R.id.showMessage)
        val textSeen: TextView = itemView.findViewById(R.id.textSeen)
    }

    override fun getItemViewType(position: Int): Int {
        val userID = FirebaseAuth.getInstance().currentUser!!.uid
        return if(MessageList[position].userID==userID)
        {
            right
        }else
        {
            left
        }
    }
}

Model Class

package com.aarondcosta99.foodreuseapp.model

data class Message(var userID:String? = "",var message:String? = "",var recID:String? = "",var isSeen:Boolean=false)

Firestore database image

CodePudding user response:

This won't work:

rootRef.collection("chats").document(roomID).collection("messages").document().update("isSeen",true)

The document() call without any arguments creates a reference to a new non-existing document, which you then try to update. But update() only works when a document already exists, you can't use update() to create a document, so this code ends up doing nothing.

To update a document, you need to specify the complete path to that document. The fact that you need to update a lot of documents makes no difference to that fact, it just means you'll need to paths to a lot of documents.

As far as I can tell, you are trying to update the document that you read in documentSnapshots, which means you already have the DocumentReference handy and can update it with:

queryDocumentSnapshots.reference.update("isSeen",true)
  •  Tags:  
  • Related