Ad
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.
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
Ad
Answer
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();
}
}
Ad
source: stackoverflow.com
Related Questions
- → should I choose reactjs+f7 or f7+vue.js?
- → Phonegap Android write to sd card
- → Local reference jquery script in nanohttpd (Android)
- → Click to navigate on mobile devices
- → How to allow api access to android or ios app only(laravel)?
- → Access the Camera and CameraRoll on Android using React Native?
- → React native change listening port
- → What is the default unit of style in React Native?
- → Google play market autocomplete icon
- → Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`
- → Using Laravel with Genymotion
- → react native using like web-based ajax function
- → react native pdf View
Ad