I am trying to get data from the following collection "Buses" if say Bus_Driver=="xyz".
My Firebase test looks like this:
I am getting database reference with this code:
busInfoReference= FirebaseDatabase.getInstance().getReference("Buses");
The following loop I've applied does not work correctly:
for(DataSnapshot ds : dataSnapshot.getChildren()){
busInfo = ds.getValue(BusInforamtion.class);
if(ds.exists()) {
if(busInfo.getBus_Driver().equalsIgnoreCase(driverName))
{
saveData()
break;
//}
}
}
How can I apply loop to get the required data? Thanks in advance.
To solve this, you need query your database like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Buses").orderByChild("Bus_Driver").equalsTo("xyz");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String Bus_Driver = ds.child("Bus_Driver").getValue(String.class);
Log.d(TAG, Bus_Driver);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will contain all bus driver names.
Related
I'm trying to get these values in the node panadol and profinal. but it's not working.
I was able to get the date successfully. Here's my code
for(final String id: MedicinesListActivity.orderIdsList){
//get the date of the order
DatabaseReference dateReference = FirebaseDatabase.getInstance()
.getReference("Orders").child(id);
dateReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//date
String date = dataSnapshot.child("date").getValue(String.class);
Log.i("Date", date);
//loop through all the products in the specific order id
for(DataSnapshot s : dataSnapshot.child(MedicinesListActivity.userId).child("panadol").getChildren()){
Order order = s.getValue(Order.class);
Log.i("Item_Name", ""+ order.getName());
}
}
});
}
MedicineListActivity.orderIds -> contains all the orderIds i want to loop through
and the class Order contains the name and the orderQuantity.
But it's not working.
To solve this, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Orders").child(id).child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String orderQuantity = ds.child("orderQuantity").getValue(String.class);
Log.d("TAG", name + "/" + orderQuantity);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be:
panadol/3.0
profinal/2.0
Or using the Order class:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Orders").child(id).child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Order order = ds.getValue(Order.class);
Log.d("TAG", ds.getName() + "/" + ds.getOrderQuantity);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result will be the same.
In both cases, you have to use all node names in your reference to be able to display that data.
It seems like under each user's node, you have a list of named products (panadol, profinal). Your code looks up one named product panadol in that list with dataSnapshot.child(MedicinesListActivity.userId).child("panadol"):
//loop through all the products in the specific order id
for(DataSnapshot s : dataSnapshot.child(MedicinesListActivity.userId).child("panadol").getChildren()){
Order order = s.getValue(Order.class);
Log.i("Item_Name", ""+ order.getName());
}
Since you then iterate over the child nodes of panadol, your s snapshot refers to the individual properties of panadol: name and orderQuantity. But your code seems to try to map each of those properties to an entire Order object, which won't work.
You have two options:
Show the individual properties, without using the Order class:
for(DataSnapshot propSnapshot: dataSnapshot.child(MedicinesListActivity.userId).child("panadol").getChildren()){
Log.i("Item_Name", propSnapshot.getKey() + "="+ propSnapshot.getValue());
}
Don't use the loop, and get the products and their properties in an Order object:
for(DataSnapshot propSnapshot: dataSnapshot.child(MedicinesListActivity.userId).getChildren()){
Order order = s.getValue(Order.class);
Log.i("Item_Name", propSnapshot.getKey() + "="+ propSnapshot.getValue());
}
I am trying to create child inside child -LoVaDPuBRr4K2JSkc_j , but how?
Code :
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseDocument = firebaseDatabase.getReference(firebaseAuth.getUid()).child("Document");
To create a child in -LoVaDPuBRr4K2JSkc_j, you can do:
databaseDocument.child("-LoVaDPuBRr4K2JSkc_j").child("newProperty").setValue("new value");
If you want to generate a new child with an auto-generated key, it'd be:
databaseDocument.child("-LoVaDPuBRr4K2JSkc_j").push().setValue("new value");
Both of these assume that you know the -LoVaDPuBRr4K2JSkc_j value in your code. This is required to be a able to add a child, as writing to a location in the database requires that you know the full path to that location.
You'll not want to hardcode this key of course, so there are two common options to have the key:
Pass it along your app from the moment when you loaded the data.
Use some other value of the node that allows you to perform a query on the database to look up the key.
The simplest solution to add a new property inside your -LoVaDPuBRr4K2JSkc_j object would be use that pushed id in your reference like in the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child(uid).child("Document").child("-LoVaDPuBRr4K2JSkc_j");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getRef().child("newProperty").setValue("newValue");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
Edit:
Accodring to your comment, if you have more than one key, then you should use a query. The following code will do the trick:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child(uid).child("Document").orderByChild("inspectorName").equalTo("Test");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ds.getRef().child("newProperty").setValue("newValue");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
My code and its work :
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseProduct = firebaseDatabase.getReference(firebaseAuth.getUid()).child("Document");
String id = databaseProduct.push().getKey();
final String productID = databaseProduct.child(id).child("Product").push().getKey();
final Items items = new Items(productID, dates, nameInspector, locate, product, priceProduct, amount, code);
databaseProduct.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot getDocumentKey : dataSnapshot.getChildren()) {
String getDocumentID = getDocumentKey.getKey();
String sameDocumentID = getDocumentKey.child("documentID").getValue().toString();
if (getDocumentID.contentEquals(sameDocumentID)) {
databaseProduct.child(getDocumentID).child("Product").child(productID).setValue(items);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I am looking for a way to get data from the firebase real-time database in a format like an array[] or a String.
My database looks like this:
Link to image of database
Or:
Database
|
-->Users
|
-->UID1
-->UID2
This is at the root of the database
I want to get a list of all of the UIDs in the "Users" child.
This is the code I have so far and am a bit stuck on:
DatabaseReference databaseReference = firebaseDatabase.getReference("Users");
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String UIDs = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am a bit of a rookie as it comes to java, android studio, and firebase. I am trying to get the data in a format I know how to use like a String or an Array[] of Strings. I looked around if other people had maybe asked the same question, but I could get the answers to those questions to work/didn't understand them.
Thanks in advance for your time!
To get the a list of uids, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
list.add(uid);
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
I recommend you to use the list only inside the callback otherwise it will be empty. If you want to use it outside the onDataChange() method, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
For your above question I will give both ways: ArrayList or String with delimiters
ArrayList<String> uids = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids.add(snapshot.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
For String
String uids = "";
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids += snapshot.getKey() + ",";
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
This gives an output such as: uid1,uid2,uid3,.....uidn,
You can try this:
DatabaseReference ref=
FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int i = 0;
for(DataSnapshot d : dataSnapshot.getChildren()) {
name[i] = d.getKey();
i++;
}
}
}//onDataChange
#Override
public void onCancelled(DatabaseError error) {
}//onCancelled
});
name[] is an array of strings!
I have the following database. What I need is to get the total count of comments per post when posting UID equal to current_user_uid.
Any suggestion on how to do this?
To solve this, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Posts").orderByChild("uid").equalTo(current_user_uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
long count = ds.child("comments").getChildrenCount();
Log.d("TAG", "Count: " + count);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);
So I have some data in my Firebase. It's structure is
(assume that there is more data)
I want to get the records where banknoteType ="100_dollar" and userId="1057..."
DatabaseReference database = FirebaseDatabase.getInstance().getReference("userBanknoteAmount");
Query firebaseQuery = database.orderByChild(1057...).equalTo(1057...);
firebaseQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//todo
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("onCancelledError", "loadPost:onCancelled", databaseError.toException());
}
});
But the onDataChangeevent doesn't fire... What am I mistaking?
EDIT: I am trying to debug it and neither onDataChange nor onCancelled breakpoints stop there
EDIT 2 : The current code I am using is
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userBanknoteAmountRef = rootRef.child("userBanknoteAmount");
Query firebaseQuery = userBanknoteAmountRef.orderByChild("userId");//.equalTo(userId);
firebaseQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.d("test", "onDataChange: "+postSnapshot);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.wtf("onCancelledError", "loadPost:onCancelled", databaseError.toException());
}
});
EDIT 3: https://i.stack.imgur.com/iBkcx.png
Firebase Realtime database does not allow you to chain multiple filter methods. If you want to get the records where : userId="1057...", please change the following line of code:
Query firebaseQuery = database.orderByChild(1057...).equalTo(1057...);
with
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userBanknoteAmountRef = rootRef.child("userBanknoteAmount");
Query firebaseQuery = userBanknoteAmountRef.orderByChild("userId").equalTo(1057...);
If you want to get all the records where banknoteType ="100_dollar" and userId="1057...", please see my answer from this post.
According to your edited post, please also change this line of code:
Log.d("test", "onDataChange: "+postSnapshot);
to
Log.d("test", "onDataChange: "+postSnapshot.child("userId").getValue(String.class));