Issue
I'm making a game, so far I've made two buttons for the test. The first button makes a win, and the second one loses, all this is added to the database.
alt="enter image description here" />
int win_int = 0;
int lose_int = 0;
The fact is that every time you enter this activity, the number is reset to zero, since I set the number 0 in the variable. I want to understand how to make "integer" take a number not just one, but the number that is in the database.
Here are the codes for the two buttons:
Button win = (Button)findViewById(R.id.Poke);
win.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
winsRef = database.getReference();
winsRef.child("players/").child(playerName).child("/wins").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getRef().setValue(win_int = win_int + 1);
Toast.makeText(DuelGame.this, "+1 win!", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(DuelGame.this, "Data error!", Toast.LENGTH_SHORT).show();
}
});
}
});
Button lose = (Button)findViewById(R.id.lose_POKE);
lose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
losesRef = database.getReference();
losesRef.child("players/").child(playerName).child("/loses").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getRef().setValue(lose_int = lose_int + 1);
Toast.makeText(DuelGame.this, "+1 Lose!", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(DuelGame.this, "Data error!", Toast.LENGTH_SHORT).show();
}
});
}
});
In general, I want that every time I enter the activity, the number is not reset to zero, and Integer takes the number from the database and is based on them, and not on zero in the variable.
Solution
If you want to increment a value in the database, you can use the atomic increment operation:
Map updates = new HashMap();
updates.put("wins", ServerValue.increment(1));
database.getReference().child("players/").child(playerName).updateChildren(updates);
Answered By - Frank van Puffelen
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)