0

I have an activity that registers active time data to my Firebase Realtime Database, this is input manually using an EditText which then displays it to a TextView in the UI. This is all working fine, however, if I was to put more data in, it would simply replace the value in the database and TextView.

I have previously done something similar to this in another activity (Adding (Sum) multiple Firebase child values together to give a total value?), however, this activity had additional nodes with dates, etc so the same approach would not work in my current activity. Ideally, I would have this node organized with dateStrings etc, however, for demonstration purposes, it's not necessary. Therefore I would just like to take whatever value is already existing in the database and add to it the input value, then restore that to the database.

It's probably quite simple but I've been staring at it so long I've confused myself. This is nowhere near right but just a bit confused about my next steps.. I've seen perhaps something along these lines how to sum money value in firebase realtime android studio but wondering if this is the easiest way?

Register Activity method:

    registerActivity.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String activityTime = activeMinutes.getText().toString().trim();
            databaseReference.child("active time").setValue(activityTime);
            addActivity.setVisibility(View.VISIBLE);
            registerActivity.setVisibility(View.GONE);
            activeTimeTI.setVisibility(View.GONE);
        }
    });

Method to display data (shortened):

    databaseReference.addValueEventListener(new ValueEventListener() {
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int total = 0;

           String activityTime = dataSnapshot.child("active time").getValue(String.class);

            if (activityTime == null) {
                activeTimeTV.setText("0");
            } else {
                total += Integer.parseInt(activityTime);
                activeTimeTV.setText(String.valueOf(total) + " minutes");
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w("TAG", "onCancelled", databaseError.toException());
        }
    });

Firebase Hierarchy:

enter image description here

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Caitlin
  • 531
  • 5
  • 19
  • I'm not sure I understand. Do you want to update a field in the database? If this is what you want, which field would like to be updated? – Alex Mamo Sep 04 '21 at 09:02
  • So for instance.. on the hierarchy, Active Time is at 500 (mins) just now, if I did another 90 mins of activity, I would like to add 90 to that value and then update that to show 590. – Caitlin Sep 04 '21 at 10:30

1 Answers1

1

According to your last comment:

Active Time is at 500 (mins) just now, if I did another 90 mins of activity, I would like to add 90 to that value and then update that to show 590.

To increment the value of "active time" by 90, first of all, you need the change the type of the field to be number. That being said, your field should look like this:

ndkdn
 |
 --- active time: 500

See, there are no quotation marks. If your "ndkdn" node is a direct child of your Firebase Realtime Database root, to increase the value by 90, simply use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference activeTimeRef = rootRef.child("ndkdn").child("active time");
activeTimeRef.setValue(ServerValue.increment(90));

This kind of operation is atomic. If you are not allowed to change the type of your field, to also have consistent data, then you should read the value first and increment it right after that using a transaction:

activeTimeRef.runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        Integer activeTime = Integer.parseInt(mutableData.getValue(String.class));
        if (score == null) {
            return Transaction.success(mutableData);
        }
        mutableData.setValue((activeTime + 90) + "");
        return Transaction.success(mutableData);
    }

    @Override
    public void onComplete(DatabaseError error, boolean b, DataSnapshot snapshot) {
        Log.d("TAG", error.getMessage()); //Don't ignore potential errors!
    }
});
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193