0

I have a Firestore collection like this:

enter image description here

Let's say I want to update the document "S4vfct...." by changing its address and cost value. Here's my code:

FirebaseFirestore firestore = FirebaseFirestore.getInstance();
final CollectionReference colRef = firestore.collection("kontrakan);

colRef.whereEqualTo("owner", OWNER_NAME).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {

            for (QueryDocumentSnapshot document : task.getResult()) {
                Map<Object, String> map = new HashMap<>();
                map.put("address", edtAddress.getText().toString());
                map.put("cost", edtCost.getText().toString());
                colRef.document(document.getId()).set(map, SetOptions.merge());
                Toast.makeText(getApplicationContext(), “Detail has been successfully updated.”, Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), “Cannot update detail.”, Toast.LENGTH_SHORT).show();
        }
    }
});

The code successfully updates the value of address, since it's a String. But doesn't change cost, because it's an int. How to fix this?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
anta40
  • 6,511
  • 7
  • 46
  • 73

1 Answers1

0

The code successfully updates the value of the address, since it's a string. But doesn't change the cost, because it's an int. How to fix this?

That's because in the following line of code:

map.put("cost", edtCost.getText().toString());

You are trying to update the "cost" property with a String value, while the "cost" property in the database is a number. To solve this, please change the above line of code into:

map.put("cost", Long.parseLong(edtCost.getText().toString()));
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • This doesn't even compiles, because map is an instance of `Map`. Hmm... – anta40 Oct 19 '20 at 17:10
  • In that case, you might consider updating using two objects one `Map` and another one `Map` or use multiple updates as explained in this **[post](https://stackoverflow.com/questions/56608046/update-a-document-in-firestore)**. Give it a try and tell me if it works. – Alex Mamo Oct 19 '20 at 18:47