Yousef Hashem
Yousef Hashem

Reputation: 37

How to update value of a specific field in Firestore document?

How do I get its ID only Android Firebase Firestore and update a specific field only?

I just want to update the 'consumption' value of electricity without updating all the data for one device.

public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    DeviceModel modal = deviceModelArrayList.get(position);

    holder.showName.setText(modal.getDeviceName());
    holder.showWat.setText(modal.getDeviceWat());
    holder.showUse.setText(modal.getDeviceUse());


    holder.addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            hours = Integer.parseInt(String.valueOf(holder.showUse.getText()));
            if (hours < 24) {
                holder.showUse.setText(String.valueOf(++hours));
                db.collection(currentUser)
                        .document()
                        .update("deviceWat", hours);
            }
        }
    });
}

enter image description here

Upvotes: 0

Views: 1060

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138814

Each time you're calling .document() without passing anything as an argument in the following reference:

db.collection(currentUser)
   .document() //👈
   .update("deviceWat", hours);

It means that you're generating a brand new unique document ID. When you call .update(), you're trying to update a document that actually doesn't exist, since you only reserved a document ID and nothing more.

If you want to create a reference that points to a particular document inside the "currentUser" collection, then you have to pass the document ID of that document, which already exists in the database, and not generate a new one. So to solve this, get the document ID of the item you want to update and pass it to the .document() function like this:

db.collection(currentUser)
   .document("hnx81...803tY") //👈
   .update("deviceWat", hours);

Upvotes: 2

Related Questions