How to retrieve json from firebase which has nested child? - java

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) {
}
});
}

Related

Firebase read subdirectory in every entry

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]

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);

Firebase database query to fetch particular data

My Database struckture
This is my database in Firebase and I'm developing an Android application. Now I want to retrieve all the data from "Generated" node where my current user's userid matches the "userId" in data.
I want to know the query in Firebase to fetch that particular data.
Firebase Query firebase query
Read the Firebase Realtime Database Documentation to get some idea firebase realtime database
To Get Current User Uid
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = user.getUid(); // user.getUid() will return null if you are not log in
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query query = db.child("Leads").child("Generated").orderByChild("userid").equalTo(current_uid);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// do something
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Or Try This One
db.child("Leads").child("Generated").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot ds: dataSnapshot.getChildren())
{
SomeClass someClass = ds.getValue(SomeClass.class);
if(someClass.getUid().equals("uid")){
// i don't if it is the best practice or not but you can do with this as well
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To access every item from that reference you will need something like this:
mDatabase.child("Leads").child("Generated").child(uid).addValueEventListener(new ValueEventListener() {
final List<String> lstItems= new ArrayList<String>();
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = (String) ds.getKey();
String values = (String) ds.getValue();
Log.e("Values",""+values );
lstItems.add(values );
}
PS: you can remove .child(uid) in your reference if you want to get all the children of Generated (it's going to be all the uids).

How to compare firebase inner child items in android without data object model?

I'm trying to validate the admin by taking text from the app. I've tried using a data object model and store the details but it is just not required. I've tried this code in other classes without the loop and it works fine.
databaseReference = FirebaseDatabase.getInstance().getReference("Preschools");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot preschool : dataSnapshot.getChildren())
{
for(DataSnapshot admin : preschool.getChildren())
{
String f_em = (String) admin.child("Admin").child("Email").getValue();
String f_pa = (String) admin.child("Admin").child("Password").getValue();
if(emailAddress.getText().toString().equals(f_em) && password.getText().toString().equals(f_pa))
{
flag = true;
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(_2_Login.this, "Unable to reach firebase", Toast.LENGTH_SHORT).show();
}
});
Logacat : Image Here
False is returned in the if condition. I'm not able to figure out the error in my logic.
Error : No break if credentials are equal.
Below is the correct code:
databaseReference = FirebaseDatabase.getInstance().getReference("Preschools");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot preschool : dataSnapshot.getChildren())
{
if(emailAddress.getText().toString().equals(preschool.child("Admin").child("Email").getValue()) &&
password.getText().toString().equals(preschool.child("Admin").child("Password").getValue()))
{flag=true; break;}
}

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