Reputation: 33
How do I get the last ID entered in Realtime?
I have something like that, and I need the ID of the last record entered in license plates.
public String buscaMatricula(){
DatabaseReference databaseReference = database.getReference().child("matriculas");
Query ultimoDado = databaseReference.orderByKey().limitToLast(1);
Log.i("teste", String.valueOf(ultimoDado));
ultimoDado.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String matricula1 = dataSnapshot.getKey();
Log.i("teste",matricula1);
System.out.println(matricula1);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}});
return matricula;
My last key entered is 9000, I want to get it in a variable
Upvotes: 0
Views: 988
Reputation: 598708
You're using numbers encoded as strings, which unfortunately means this will be tough. For keys (and string values) Firebase uses lexicographic ordering, and in that order "900"
comes after "1000"
, since "9"
> "1"
.
Your options are to:
"0900"
comes before "1000"
. You'll need to ensure that you use a length long enough to encompass all values you expect.With either of those two changes to the data model, you can get the last key with:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(".../.../matriculas");
Query query = rootRef.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
System.out.println(childSnapshot.getKey());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
Upvotes: 2