Firebase read subdirectory in every entry - java

How can I get a list of all "Floor" elements in my database. If I use the following database my list should have 3 elements. List should contain the elements with the id's 1234, 4321, 2341.
mydatabase
-buildings
--LNBxRoNBhVZyXniqe9t
---checked
---anzI
---anzA
---floors
----f1
-----1234
------description
------id
----f2
-----4321
------description
------id
--LXdsafRfasdf12asdfJ
---checked
---anzI
---anzA
---floors
----f1
-----2341
------description
------id
This is my DAO:
private FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("buildings");
#Override
public void initialize() {
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
List<Floors> list = new LinkedList<>();
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
????
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}});

You will need to traverse the DataSnapshot that you get from Firebase. Something like this
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot buildingSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot floorSnapshot: buildingSnapshot.child("floors").getChildren()) {
for (DataSnapshot numberSnapshot: floorSnapshot.getChildren()) {
Log.i(TAG, numberSnapshot.getKey()); // "1234", "4321", "2341"
Log.i(TAG, ""+numberSnapshot.child("id").getValue());
}
}
}
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});

How can I get a list of all "Floor" elements in my Database?
In a very simple way, by iterating the database using getChildren() method three times.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference buildingsRef = rootRef.child("buildings");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.child("floors").getChildren()) {
for(DataSnapshot d : ds.getChildren()) {
String key = d.getKey();
String description = d.child("description").getValue(String.class);
list.add(key);
Log.d("TAG", key);
}
}
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage());
}
};
buildingsRef.addListenerForSingleValueEvent(valueEventListener);
List should contain the elements with the id's 1234, 4321, 2341
The list will contain those exact three ids. If you try to print the list in your logcat, the result will be:
[1234, 4321, 2341]

Related

How to find firebase all children details from different users?

I want to show all product child details. but I was unable to do so. I am new to firebase and wish to complete my university project I need to use firebase.
each user has a single or multiple products. I can show all shops from a single user but I want to show all products from all user.
private void loadShopProducts() {
productList = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(shopUid).child("Products")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
productList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()){
ModelProduct modelProduct = ds.getValue(ModelProduct.class);
productList.add(modelProduct);
}
adapterProductBuyer = new
AdapterProductBuyer(ShopDetailsActivity.this, productList);
productRv.setAdapter(adapterProductBuyer);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Basically, I need to pull out all the children from users who are the seller.
private void loadAllProduct(){
productList = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
productList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()){
String uid = ""+ds.getRef().getKey();
DatabaseReference ref = (DatabaseReference) FirebaseDatabase.getInstance().getReference("Users").child(uid).child("Products");
// ref.addValueEventListener(new ValueEventListener() {
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
productList.clear();
if (dataSnapshot.exists()){
for (DataSnapshot ds : dataSnapshot.getChildren()){
ModelProduct modelProduct = ds.getValue(ModelProduct.class);
productList.add(modelProduct);
}
adapterProductShow = new AdapterProductShow(MainBuyerActivity.this, productList);
showAllProductRv.setAdapter(adapterProductShow);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

How to retrieve json from firebase which has nested child?

I have imported json file to firebase real-time database you can follow the screenshot
https://ibb.co/wyLDPC8 "database structure"
You can do it in this way
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
dbRef.child("categories").addSingleValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String name = snapshot.child("names").getValue().toString(); // it will give names node string
/// To Fetch Quotes
DataSnapshot quotesSnapshot = snapshot.child("qoutes");
for (DataSnapshot quoteSingleSnpashot : quotesSnapshot.getChildren()) {
String quote = quoteSingleSnpashot.child("quote").getValue().toString(); // it will give names node string
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Unable to get just one key at a time from the node "History"

{
"History" : {
"-LIRZ4Nf2HyTTYtZEeOA" : {
"destination" : "101 Main Street, Your Town, Your Country",
"driver" : "vP9r4F2yDWRRuvKjRiQvMEXVuoK2",
"payment response" : "approved",
"rating" : 0,
"ridePrice" : 3.63,
"rider" : "C0RjB5NPZcTvWz9XiUAhpTDOK0C2",
"status" : "accepted",
"timestamp" : 1532709012
}
}
The above is the History node in my Firebase database.
My ultimate goal is to send an alert dialog once the payment response = "approved" but, in this case, when there is more than one key in the History node, the alerts run on top of each other.
What can I do so this does not happen?
The code I am using to get the key for each History entry is:
private void getPaymentResponse() {
final DatabaseReference paymentConfirmed = FirebaseDatabase.getInstance().getReference("History");
paymentConfirmed.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ryydeKey = ds.getKey(); **<-- gets the key**
DatabaseReference response = FirebaseDatabase.getInstance().getReference("History")
.child(ryydeKey);
response.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getKey().equals("payment response")) {
String response = String.valueOf(child.getValue().toString());
if (response.equals("approved")) {
proceedToPickupDialog();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I am assuming that the code:
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ryydeKey = ds.getKey();
is getting all the keys, but all I want is the present key.
Edit
I am putting in this code and nothing is printing up. Tried logs and toasts.
DatabaseReference payRef = FirebaseDatabase.getInstance().getReference();
Query query = payRef.child("History").orderByChild("driver").equalTo(driverId).limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String response = ds.child("payment response").getValue(String.class);
Log.e(TAG, "response = " + response);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
When you are using getChildren() method, it means that you are looping through the entire DataSnapshot object. If the DataSnapshot contains more then one child, then the alerts will run on top of each other. If you want to check only for a particular child, you need to change the code a little bit.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference idRef = rootRef.child("History").child("-LIRZ4Nf2HyTTYtZEeOA");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String response = dataSnapshot.child("payment response").getValue(String.class);
if(response.equalTo("approved")) {
Log.d("TAG", "Payment approved!");
} else {
Log.d("TAG", "Payment not approved!");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
idRef.addListenerForSingleValueEvent(valueEventListener);
Using this code, you get only the response form a single child. To actually get this work done, first you need to store this value -LIRZ4Nf2HyTTYtZEeOA in a variable in order to be able to use in your reference.
Edit: This another approach using a query"
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("History").orderByChild("driver").equalsTo(driverId).limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String response = dataSnapshot.child("payment response").getValue(String.class);
if(response.equalTo("approved")) {
Log.d("TAG", "Payment approved!");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);

How i can get a value in firebase

I have a database that looks like this:
And my code like this:
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot uniqueKey:dataSnapshot.getChildren()) {
for (DataSnapshot keysiswa:uniqueKey.getChildren()) {
for (DataSnapshot valuesiswa:keysiswa.child("nama_siswa").getChildren()) {
String c = valuesiswa.getValue().toString();
Log.i(TAG,c);
}
}
}
}
I want to take the value of "nama_siswa" but nothing happens in logcat. What is wrong with my code?
Try this code.
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("siswa");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("Name:",dataSnapshot.getValue(User.class).name); // define your pojo class
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To get the value of nama_siswa property, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference siswaRef = rootRef.child("siswa");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String nama_siswa = ds.child("nama_siswa").getValue(String.class);
Log.d("TAG", nama_siswa);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
siswaRef.addListenerForSingleValueEvent(valueEventListener);
The output will be:
chandra
coba

Firebase data retrieve with singlechildevent

Here is my firebase data structure . The child "Tags" is a child of root.
final Query searchquery = mDatabase.child("Tags").orderByKey().limitToFirst(10).startAt(s.toString().toLowerCase()).endAt(s.toString().toLowerCase() + "\uf8ff");
searchquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String u = dataSnapshot.child("article_name").getValue(String.class);
Toast.makeText(MainActivity.this,":/ : "+u.toString(),Toast.LENGTH_LONG).show();
}catch (Exception tg){
Toast.makeText(MainActivity.this,tg.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get the value of child "article_name" . I used the code above . But it is returning null .
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tagsRef = rootRef.child("Tags");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String article_name = ds.child("article_name").getValue(String.class);
Log.d("TAG", tagsRef);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
tagsRef.addListenerForSingleValueEvent(eventListener);
The output will be:
Blood Circulation
Dummy Article
Also don't forget to use names for the keys that does not contain any spaces. So you need to change blood circulation in blood_circulation or bloodCirculation

Categories

Resources