Get last node in Firebase database Android - android

I want to get item in the last node added in firebase database from my Android. You can see on the image below i'm not sure how to get the specific node, because unique key is created by Firebase. How to reference to auto-created node and child inside? Thanks a lot
The last node

Try this:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query lastQuery = databaseReference.child("mp").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("message").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Handle possible errors.
}
});
Hope this helps!

This might work:
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("mp");
Query query = db.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User key", child.getKey());
Log.d("User val", child.child("message").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO: Handle errors.
}
});

I prefer to write and retrieve data through objects.
MyObject is POJO.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
MyObject myObject = data.getValue(MyObject.class);
Log.i(TAG, data.getKey() + " = " + myObject.toString());
}
}

console.log('last messages', messages[messages.length-1]);

Related

Firebase query in tree with depth and multiple children

I have a problem regarding querying the firebase database using a value and getting the specific node. My schema is shown here:
In my schema 'workLocations' belongs to an 'excavationWorks', and 'excavationWorks' belongs to an 'excavationLists'.
That means that the path to a specific workLocation is excavationLists/excavationWorks/workLocations/(specific workLocation)
The problem that I have is that I want to query the workLocations node by the location value (let's say London) and get the parent node (the red circled key which is the key of the specific workLocation).
I have search and read many posts but I haven't managed to make it work.
My code looks like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("workLocations").orderByChild("location").equalTo("London");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot workLoc : dataSnapshot.getChildren()) {
// do something with the individual "issues"
Log.d(TAG, workLoc.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you
To achieve this, you need to query your database twice like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
DatabaseReference workLocationsRef = reference
.child("excavationLists")
.child("excavationWorks")
.child("workLocations");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String key = ds.getKey();
Query query = workLocationsRef.child(key).orderByChild("location").equalTo("London");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String description = snapshot.child("description").getValue(String.class);
Log.d("description", description);
String partentKey = snapshot.getRef().getParent().getKey();
Log.d("partentKey", partentKey);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
workLocationsRef.addListenerForSingleValueEvent(valueEventListener);

Displaying the database nodes from Firebase in a list in Android

A simple question:
Referring to my database image, I want to get the values of the children of node "user" in a list in an Activity, i.e. values "a" and "m" should be displayed in the list.
What should I use and how?
Please try this code:
DatabaseReference yourRef = FirebaseDatabase.getInstance().getReference().child("user");
yourRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> usersList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String userName = (String) ds.getKey();
usersList.add(userName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
This is the way in which you'll have in your list, a, m ans so on.
Hope it helps.
You can get the info from the docs here
List<User> allUsers = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("user");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
allUsers.clear();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
allUsers.add(userSnapshot.getValue(User.class));
}
yourRecyclerViewAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Users failed, log a message
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
// ...
}
});

How to retrieve the custom push id from fire base database?

I am having trouble fetching the custom push id which is created while pushing the value.
I want to fetch "4wJIGRCkYrZqFpb401hSmgHeBOI3" from rated_user node. Any help will be really useful. Thanks in advance.
Lets say database reference for rated_users is this RatedUser
valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
String key = postSnapshot.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
RatedUser.addValueEventListener(valueEventListener);
Use the following code to archive your goal.
private DatabaseReference ref;
ref = FirebaseDatabase.getInstance().getReferenceFromUrl("https://xxxx.firebase.com/rated_users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String key = dataSnapshot.getKey();
String value = dataSnapshot.child("key").getValue(String.class);
}catch (Exception e) {
String valws = e.getMessage();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
PS:
I did a quick sample it works for me.
All i did was added a foreach loop:
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
Log.e("children" , snapshot.getKey()+"");
}
this gave me the key "4wJIGRCkYrZqFpb401hSmgHeBOI3"

How to access one key of JSON tree from Firebase Realtime Database?

I want to get the value of 'caste' key from the JSON tree in Firebase Realtime Database.See this image
I have the user's unique ID and all my auth and user objects are in place. How do I get a reference to only the 'caste' key into a String variable?
Thanks,
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("project-android-536f3");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
String caste = (String) messageSnapshot.child("caste").getValue();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I figured it out. I never provided the unique User ID so it never got data from the database.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference(firebaseUser.getUid()).child("caste");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
caste = dataSnapshot.getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Retrieving specific node from firebase database in android

I am trying to use Firebase in my android application. I need to get an object, i am searching with its email (attribute in the object).
this is my code of search:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Remorqueur");
Query queryRef=myRef.orderByChild("email").equalTo(ed_mail.getText().toString());
If the object exists in my database I need to get the whole object back! how can I do it?
should be able to do something like following
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
MyPojo app = childSnapshot.getValue(MyPojo.class);
}
Try this Please
DatabaseReference dbRef = firebaseDatabase.getReference("Remorqueur");
Query query = profileDbRef
.orderByChild("email")
.equalTo(ed_mail.getText().toString());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Log.d(TAG, dataSnapshot1.getKey() + " " + dataSnapshot1.getValue(Profile.class)
.toString());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Categories

Resources