traverse through unique id to get children - java

If my tree looks like that:
{
unique_id_1: {
message: "hello"
}
unique_id_2: {
message: "hi there"
}
}
How do I get all messages that are children of each unique id if I don't know the user's unique id? Or I have to build my database so that a message can only be a direct child of a unique id and then traverse like so:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference reference = database.child("message");
Or that would not work?

To get all the messages, you need to loop:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String messages = datas.child("message").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here the datasnapshot is at the root node then if you have unique ids and don't have there values, you can just loop inside these unique ids dataSnapshot.getChildren() and get the messages.
You can also retrieve the unique ids by doing String key = datas.getKey();

Related

How do you append to an array list in realtime database?

I have a database of users with their emails, role and list of contacts.
I have code to add contacts that when you input into the EditText, it checks through the database if the email exists and if it does, it appends the email into the contacts list. However, nothing gets added in my database.
public void searchContacts(final String emailInput){
final DatabaseReference users;
users = FirebaseDatabase.getInstance().getReference("users");
users.orderByChild("email").equalTo(emailInput).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
if((userSnapshot.child("email").getValue(String.class).equals(emailInput))){
users.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("contacts").child(emailInput).setValue(true);
}
}
}
Nothing is added, because you haven't create a list yet. To solve this, please use the following code:
public void searchContacts(final String emailInput){
DatabaseReference users = FirebaseDatabase.getInstance().getReference("users");
users.orderByChild("email").equalTo(emailInput).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>(); //Create the list
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
String email = userSnapshot.child("email").getValue(String.class);
if(email.equals(emailInput)){
users.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("contacts").child(emailInput).setValue(true);
list.add(email); //Add the email the list
}
}
//Do what you need to do with list
}
}
}

fetching data from firebase without using primary key of the table

I want to retrieve posts posted by currently loggedin user. But with current code all the posts are getting retrieved. How to retrieve expected data by using the uid from customer table?
post_id is primary key of Customer table not customerid(uid).
Get a reference of the current user and use it to query post posted by the user like this:
FirebaseUser user =FirebaseAuth.getInstance().getCurrentUser();
Query reference;
reference = FirebaseDatabase.getInstance().
getReference("customers").orderByChild("customerId").equalTo(user.getUid());
reference.addListenerForSingleValueEvent(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String
customerId =datas.child("customerId").getValue().toString();
String
customerName =datas.child("customerName").getValue().toString();
String
phone =datas.child("phone").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try like this ,
Step 1. Get the right child node , and query on it by getting the current logded user uid:-
String currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("customers").orderByChild("customerId").equalTo(currentLoginId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
List<Customers> customers = new ArrayList<>();
while (dataSnapshots.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshots.next();
Customers user = dataSnapshotChild.getValue(Customer.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Android, Firebase - database only returns single child node as string when trying to retrieve multiple child nodes

I've just started trying to use Firebase in my Android application. I can write data into the database fine but I'm running into a problem when trying to retrieve data.
My database is structured as below
My method for retrieving the data:
public void getCurrentUserData() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser loggedUser = firebaseAuth.getCurrentUser();
String uid = loggedUser.getUid();
DatabaseReference userRef = database.getReference().child("Users").child(uid);
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//crashes because user is not a string
//User user = dataSnapshot.getValue(User.class);
//works because function is returning first child of uID as a string
String user = dataSnapshot.getValue().toString();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
When debugging:
dataSnapshot = "DataSnapshot { key = bio, value = test }"
I was expecting this to return all children contained within uid (bio, dob, firstName, joinDate, lastName, location) and put them into my User object but it actually looks as if its only returning the first child node (bio) as a string.
Why is this happening and how do I retrieve the full set of child nodes?Any help appreciated. Thanks.
If you want to get all properties of the user, you will either need to create a custom Java class to represent that user, or you will need to read the properties from the individual child snapshots in your own code. For example:
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String firstName = dataSnapshot.child("firstName").getValue(String.class);
String lastName = dataSnapshot.child("lastName").getValue(String.class);
...
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
Alternatively you can loop over the properties with:
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot propertySnapshot: dataSnapshot.getChildren()) {
System.out.println(propertySnapshot.getKey()+": "+propertySnapshot.getValue(String.class));
}
}

Retrieve data to text view from fire base without parent key

This is firebase database details
Here I want to search details using child without use parent key. According to this database, I want to get price and category using Name without using parent key ("kjhsfkgkrlhg"), ("get price, category where Name="super Creamcracker")
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference itemsRef = rootRef.child("Items");
Query query = itemsRef.orderByChild("Name").equalsTo("super Creamcracker");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String category = ds.child("Category").getValue(String.class);
long price = ds.child("Price").getValue(Long.class);
Log.d("TAG", category + " / " + price);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
So the ds contains a list of results. Even if there is only a single result, the ds will contain a list of one result. So the output will be:
200g / 200
First, you make database reference first
DatabaseReference itemRef = FirebaseDatabase.getInstance().getReference("Items");
then,
String itemName = "super Creamcracker";
Query query = itemRef.orderByChild("Name").startAt(itemName).endAt(itemName+ "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
//if you dont have class for item
String price = data.child("Price").getValue().toString();
String category = data.child("Category").getValue().toString();
//if you have class, lets say Item.java
Item item = data.getValue(Item.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Retrieve specific child values when know other child value in firebase

I want to retrieve all the doctors' "Firstname" and "Lastname" when I know the "Speciality" of doctor.That's mean when I select specific Specialty area of doctor I want to get all the doctors names which have that Specialty.
To be able to do that try the following:
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference().child("User").child("doctor");
dbRef.orderByChild("Spciality").equalTo("Pathologist").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String firstName=datas.child("Firstname").getValue().toString();
String lastName=datas.child("Lastname").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
the snapshot is at child doctor then to retrieve based on the speciality value you need to use the query orderByChild("Spciality").equalTo("Pathologist") to be able to do that. You can change Pathologist as per your requirement.

Categories