0

OKay, i have 1 key:value in firebase

hp_current: 1000

I want that when the button is clicked, the value decreases by a given number, for example, by 20 I decided to try it like this

FirebaseDatabase.getInstance().getReference("raids/$raid_squad/").addListenerForSingleValueEvent(AppValueEventListener{
 val raid = it.getValue(Raid::class.java)
val currenthp = raid!!.hp_current
 val newhp = currenthp - damage
FirebaseDatabase.getInstance().getReference("raids/$raid_squad/hp_current/").setValue(newhp.toInt())})

But the problem appears when 2 or 3 clients simultaneously click on the button and the HP does not decrease for all 3 clicks, but only for 1 of 3 clicks. Because to reduce it, it takes the old value and it turns out that it does not reduce it in any way because of other clients

I'm new to this, please help what ideas do you have?

p.s I have no problems with saving to the database! There is a problem with the fact that a lot of people should be able to just take and decrease 1 and the same value

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • You need a transaction for that, as explained in the duplicate answer. – Alex Mamo Mar 08 '21 at 09:39
  • I have no problems with saving to the database! There is a problem with the fact that a lot of people should be able to just take and decrease 1 and the same value @Alex Mamo –  Mar 08 '21 at 09:41
  • ServerValue.increment? –  Mar 08 '21 at 09:41
  • it's for JS. not Android / kotlin –  Mar 08 '21 at 09:43
  • No, it's for Android. – Alex Mamo Mar 08 '21 at 10:05
  • @Alex Mamo it didn't help, it just got worse –  Mar 08 '21 at 11:09
  • "it just got worse" is really hard to help with. Please update your question showing what you tried, and what the problem is that you're getting. I also highly recommend reading [how to create a minimal, complete, verifiable example](http://stackoverflow.com/help/mcve), as it has great guidance on how to maximize the chances that someone can help. – Frank van Puffelen Mar 08 '21 at 16:00
  • @Frank van Puffelen I have already solved my problem to some extent, I decided to make a different value for each one and when displaying it, I just took and combined all the individual values –  Mar 08 '21 at 16:36

0 Answers0