Update value of a field with Firestore and Android Studio

0

I have a table called Score, which has two records: score1 and score2.

In Android Studio I have a two-button activity, where the first button will save the value of score1 and the second button of score2.

What I want to achieve is that after pressing the first button (which will create the record), when you press the second button, change the value.

Once I perform the actions, it looks like this:

I have the code for the first button, but I do not know how to program the second one. It should be noted that in the first button register the two values, that's why I want the second button to update the second value.

        int score1 = Integer.parseInt("1");
        int score2 = Integer.parseInt("0");


        CollectionReference dbPuntaje = db.collection("puntaje");

        Puntaje puntaje = new Puntaje(score1, score2);

        dbPuntaje.add(puntaje).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Toast.makeText(prueba.this, "Score added", Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(prueba.this, "Score no added", Toast.LENGTH_SHORT).show();
            }
        });

Thanks in advance.

    
asked by Milagros 24.09.2018 в 22:04
source

1 answer

0

As far as you got, I see it well, the steps to follow would be:

1) Obtain the auto-generated Id by firestore in order to consult or modify the data you added. This you can do very easily using the DocumentReference that gives us the SuccessListener

puntajeId = documentReference.getId();

2) with the id now we can make a reference to that document and modify it using update . I put the code that should go inside the onClick of the option2 button

CollectionReference refNuevoPuntaje = db.collection("puntaje").document(puntajeId);
refNuevoPuntaje.update("score2",1).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "DocumentSnapshot successfully updated!");
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "Error updating document", e);
        }
    });
    
answered by 26.09.2018 / 00:00
source