How to get child of child value from firebase in android?
To access a value in your database, you create a DatabaseReference
for that location. Here are three references to locations in your database:
DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("ZONES");
DatabaseReference zone1Ref = zonesRef.child("ZONE_1");
DatabaseReference zone1NameRef = zone1Ref.child("ZNAME");
In this snippet:
zonesRef
points to/ZONES
zone1Ref
points to/ZONES/ZONE_1
zone1NameRef
points to/ZONES/ZONE_1/ZNAME
See the Firebase documentation on getting a database reference for more information.
You can attach a listener to each of the references, to get the value at that location. For example, to get the value of the /ZONES/ZONE_1/ZNAME
:
zone1NameRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, dataSnapshot.getValue(String.class));
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
For more on this type of read operation, see the Firebase documentation on reading values.
If you instead listen on /ZONES/ZONE_1
, you will get a DataSnapshot
of the entire node with all its properties. You then use DataSnapshot.child()
to get the ZNAME
from it:
zone1Ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, dataSnapshot.child("ZNAME").getValue(String.class));
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
One more level up, you can listen on /ZONES
, which will get you a snapshot with all the zones. Since this handles multiple children, you will need to loop through them with DataSnapshot.getChildren()
:
zonesRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot zoneSnapshot: dataSnapshot.getChildren()) {
Log.i(TAG, zoneSnapshot.child("ZNAME").getValue(String.class));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
For more on this, see the Firebase documentation on listening for lists of data.
Finally, you might want to query to find a specific zone, for example to find the zone with "ZCODE": "ECOR"
:
Query zonesQuery = zonesRef.orderByChild("ZCODE").equalTo("ECOR");
zonesQuery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot zoneSnapshot: dataSnapshot.getChildren()) {
Log.i(TAG, zoneSnapshot.child("ZNAME").getValue(String.class));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
To learn more about this, read the Firebase documentation on sorting and filtering data.
How to get child of child value from firebase whose parent value is unknown in java
After reading the various answers on this topic linked above by Mr. @Frank van Puffelen and spending some times over it, the problem is finally solved now without changing my database structure.
Below is screenshot of the result which I wanted:
Here is my modified and working code :
private void retrieveData() {
final String shift = kvName.getText().toString();
final String employeeCode = empCode.getText().toString();
final DatabaseReference aparRef = dbRef.child("Apar").child(shift);
aparRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<>();
if (dataSnapshot.exists()) {
for (DataSnapshot dataS1 : dataSnapshot.getChildren()) {
if (dataS1.hasChild(employeeCode)) {
AparData aparData = dataS1.child(employeeCode).getValue(AparData.class);
list.add(aparData);
rvAPAR.setHasFixedSize(true);
rvAPAR.setLayoutManager(new LinearLayoutManager(Apar.this));
rvAPAR.setItemAnimator(new DefaultItemAnimator());
aparAdapter = new AparAdapter(Apar.this, list);
rvAPAR.setAdapter(aparAdapter);
} else {
Toast.makeText(Apar.this, "No Data Found!!", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(Apar.this, "Not Data Found!!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
How to get the child from firebase in android studio?
If you only need the value of the "Egg" property, create a reference that points to the exact property and get it's value as in following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference eggRef = rootRef.child("Users").child("Customer").child(uid).child("Order").child("Egg");
productsRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
String value = task.getResult().getValue(String.class);
Log.d("TAG", value);
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
10
If you want a user to have multiple orders, you should consider using a schema that looks like this:
Firebase-root
|
--- Users
|
--- $uid
|
--- orders
|
--- $pushedId
| |
| --- //Order details
|
--- $pushedId
|
--- //Order details
So you need to differentiate each order by calling push() method.
Edit:
According to your last comment:
I wanted to know the code for getting multiple children inside the order (Suppose Egg:10 Onion:5 and so on ) so how do I get that?
Here is your code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference orderRef = rootRef.child("Users").child("Customer").child(uid).child("Order");
orderRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String key = ds.getKey();
String value = ds.getValue(String.class);
Log.d("TAG", key + ":" + value);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
Egg:10
Onion:5
The result in the
Retrieve child node value from firebase with push keys as parent
You'll have to loop over the child nodes of the snapshot
you get:
RootRef.child("FirstReply").child(Enquiry_MessageID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot child: snapshot.getChildren()) { // loop over the child nodes
String returnSellerID = child.child("sellerId").getValue().toString();
if(returnSellerID.equals(current_user_Id)) { // use equals to compare strings
//my remaining code
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
Android - Firebase - Getting Child of Child Data
According to the data model and looking at this statement
jSettingsDatabase = FirebaseDatabase.getInstance().getReference().child("Resident").child(settingsUserID);
there's no node User
underneath /Resident/userId
. The query needs to start at the database's root which, I assume, is User
.
In order to get London, Washington, etc.
you need to adapt the code to:
jSettingsDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
...
jSettingsDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot node : dataSnapshot.getChildren()) {
// you will get all cities
String stgUserHomeName = node.getKey();
if(!"Washington".equals(stgUserHomeName)) // or whatever city you need
continue;
// add some more conditional logic to cope with the distinct subtrees that don't have the same properties
// London's Resident has more properties than Washington --> exception is thrown then
// to get the resident's data
node.child("Resident").child(userId).child("address")...
node.child("Resident").child(userId).child("image")...
// or
node.child("Resident").child(userId).getValue(Resident.class);
...
}
....
}
});
There's no user ID in your tree that is needed for this query. But it might be necessary depending on the DB's access rules. Obviously the other queries need to be adapted as well. The city names are also not values but a key (must be unique) so what is important to call DataSnapshot.getKey()
method.
In your case the whole database from the User downwards will be fetched and on the client all cities that are not needed will be thrown away. That's a waste of resources.
How to retrieve child value from firebase?
After getting the whole list from Firebase iterate them one by one to add them in the list, after the loop set them in the adapter of RecyclerView
, and set the adapter to your desired RecyclerView
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
list = new ArrayList<CallLogList>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
CallLogList logList = snapshot.getValue(CallLogList.class);
list.add(logList);
}
yourAdapter = YourAdapter(list);
yourRecyclerView.setAdapter(yourAdapter);
}
For more info, here is a full example
Note: If you are using LiveData
or Paging
then setting adapters is different, Let me know if you need more example
how to get all child with specific value from Firebase android kotlin?
You'll need to navigate over the dataSnapshot
in your onDataChange
to get to the correct child nodes.
To navigate a DataSnapshot
object you have two main approaches:
- You already know the key of the child you want to access, in which case you use the
child()
method to access that specific child node. For example, you could read the marked child in the JSON withdataSnapshot.child("Turcia/Adana/Çukurova University/Faculty of Business").children.map
, similarly to what you already tried on the reference. - You don't know the key of the child nodes, in which case you loop over the
getChildren()
property of the snapshot. For an example of the latter, see the Firebase documentation on listening for value events on a list of children.
I think you're looking for the second approach here, but in any case you're dealing with DataSnapshot
s, there are the ways to get at the data in there.
Related Topics
Android Studio - Creating Modules Without Copying Files
How to Repeat a Method Every 10 Minutes After a Button Press and End It on Another Button Press
Android - Supportmapfragment with Googlemaps API 2.0 Giving Illegalargumentexception
How to Store SQLite Database Directly on Sdcard
How to Get the Fragment Instance from the Fragmentactivity
How to Get Release Build APK File Using Proguard
How to Programmatically Clear Application Data
How to Secure Android Shared Preferences
Remove Application Icon and Title from Honeycomb Action Bar
Camera Tutorial for Android (Using Surfaceview)
List All the Files from All the Folder in a Single List
How to Get Child of Child Value from Firebase in Android
How to Crop the Parsed Image in Android
Horizontal Scrolling Grid View
Simple Mediaplayer Play Mp3 from File Path
Adb Connection by Wifi Getting Killed When a New Usb Attached/Detached
Android Share Intent for a Bitmap - Is It Possible Not to Save It Prior Sharing