I have the following structure in Firebase:
app-default-rtdb
-Rooms
-1
-nrCards: 5
-pin: 10001
-roomName: Test
-2
-nrCards: 9
-pin:10002
-roomName: Test2
When I click a button I want to locate the last record added and retrieve the value of the "pin" so in this case, it should be 10002. In Android Studio, I wrote the following code but my app crashes and the value can not be retrieved inside a parameter type int.
room_hc=new RoomSettingsHelperClass(); //the java class where I keep the attributes
ref= FirebaseDatabase.getInstance().getReference().child("Rooms");
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ref.orderByChild("pin").limitToLast(1).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
Log.i("MY INFO: ", String.valueOf(snapshot.getValue()));
int pinNumber =Integer.parseInt((String) snapshot.child("pin").getValue());
room_hc.setPin(pinNumber);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
});
When opening the messages executed it shows this:
I/MY INFO:: {2={pin=10002, nrCards=9, roomName=Test2}}
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.game.mygame, PID: 15440
java.lang.NumberFormatException: s == null
Does anybody know how to fix it? I just want to retrieve the pin value inside an int parameter.