Rodrigo Silva
Rodrigo Silva

Reputation: 33

How to get last key firebase

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.

enter image description here

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

Answers (1)

Frank van Puffelen
Frank van Puffelen

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:

  • Pad the numbers with leading zeroes until they're all the same length. For example "0900" comes before "1000". You'll need to ensure that you use a length long enough to encompass all values you expect.
  • Use Firebase's push IDs, which are precisely designed to have the expected order when lexicographically ordered.

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

Related Questions