I want to get the idNumber from the database and get the max value, then add it by 1 to increment it to the new id number base on year of birth. Is there a way for me to get the variable inside addValueEventListener to pass it to the constructor? If not, are there any other ways?
int newIdNumberInt = 0;
int idList = 0;
int max = 0;
setNewIdYear = newBirthday.substring(newBirthday.length() - 4);
setNewReg = "000";
setNewIdNumber = setNewIdYear + setNewReg;
newIdNumberInt = Integer.parseInt(setNewIdNumber);
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
Object id = map.get("idNumber");
String newOb = String.valueOf(id);
try {
List<Integer> listObject = new ArrayList<>();
if (newOb.startsWith(setNewIdYear))
idList = Integer.valueOf(newOb);
listObject.add(idList);
max = Collections.max(listObject);
newIdNumberInt = max + 1;
} catch (ClassCastException e) {
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
mCustom = new Custom(newIdNumberInt, newFirstName, newMiddleName, newLastName, newAddress, newBirthday);
key = mDatabase.child("Custom").push().getKey();
mDatabase.child(newFirstName + "-" + newLastName + "-" + randomKey).setValue(mCustom);