How to Loop All Firebase Children at Once in the Same Loop

Firebase for Android, How can I loop through a child (for each child = x do y)

The easiest way is with a ValueEventListener.

    FirebaseDatabase.getInstance().getReference().child("users")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
System.out.println(user.email);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});

The User class can be defined like this:

class User {
private String email;
private String userId;
private String username;
// getters and setters...
}

Getting all firebase data through loop

I have a firebase database where contacts are saved. I want to fetch
all the numbers of contacts and send them message one by one. I read
it could be done by a for loop but the loop only returns the last
number inserted, not all the numbers.

The problem is you're trying to set ArrayList items to TextView with a loop.

for(int i = 0; i<Userlist.size();i++){
show.setText(Userlist.get(i);
}

Setting text to TextView with loop changes TextView's text with every step of the loop so the TextView will show only the last item of the list. If you only use ArrayList for putting String into it and setting for TextView (according to your code it's), using ArrayList is useless.
Inside onDataChange() method before getting your data, create an empty String and while you're getting your data expand your String with data. At the end of for loop String text will have all data and you can set it to TextView.

dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String text = "";
for (DataSnapshot dsp : snapshot.getChildren()){
Map<String, Object> datas = (Map<String, Object>) dsp.getValue();
text += datas.get("number").toString() + "\n";
}
tv.setText(text);
}

@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});

Please tell me a method through which I can fetch all the numbers of
contacts and send them message one by one.

You have 2 options for getting your values. You can use Map or you can create your Java Object.

Using Map:

private void sendMessage(DatabaseReference dbRef) {
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
SmsManager smsManager= SmsManager.getDefault();
for (DataSnapshot dsp: snapshot.getChildren()){
Map<String, Object> datas = (Map<String, Object>) dsp.getValue();
String phoneNumber = datas.get("number").toString();
String message="I need help";
smsManager.sendTextMessage(phoneNumber,null,message,null,null);
}
}

@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}

Using Java Object:

If you want to use Java Object you need to create class which has a fields like database structure (fields has to same like contacts child).

Users.class (Java Object):

public class Users {

private String name, number, email;

public Users() {
}

public Users(String name, String number, String email) {
this.name = name;
this.number = number;
this.email = email;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getNumber() {
return number;
}

public void setNumber(String number) {
this.number = number;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}

Then you can get your data as an object.

private void sendMessage(DatabaseReference dbRef) {
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
SmsManager smsManager= SmsManager.getDefault();
for (DataSnapshot dsp: snapshot.getChildren()){
Users user = dsp.getValue(Users.class);
String phoneNumber = user.getNumber();
String message="I need help";
smsManager.sendTextMessage(phoneNumber,null,message,null,null);
}
}

@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}

Both sendMessage() methods are getting data from database according to given DatabaseReference and using your code for sending message.

How do I loop all Firebase children in React Native?

According to the code you provided, it looks like it works until this point

var ref = firebase.database().ref("testCategory");

ref.once("value")
.then(function(snapshot) {

Am I correct?

From this point, if you add a console.log(snapshot.val()) it might print an array of objects, something like this:
[ { test1: { testHeader: 'FirstHeader', testText: 'FirstText' } }, { test2: { testHeader: 'SecondSub', testText: 'SecondSub } }]

Right?

If so, you can for example store this snapshot into your state and then consume this state in your render method. Something like this:

const ref = firebase.database().ref('testCategory');

ref.once('value').then((snapshot) => {
this.setState({ categories: snapshot.val() });
});

Then in your render method:

const { categories } = this.state;

categories.map(category => <Text>{category.testHeader}</Text>)

The result in your screen should be:
FirstHeader
SecondSub

Let me know if this helped

Some links that might explain more about es6 codes I used in this example:

array map categories.map(...): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

object destructuring const { categories } = this.state: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

const instead of var const ref = ...: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

setState: https://reactjs.org/docs/state-and-lifecycle.html

arrow function (snapshot) => ...: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Some about firebase snapshots: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot

Hope it helps

How to loop through each firebase database child with python?

Just print the value at the current tree to get the whole thing

inventory = db.child("Inventories").get()
for business in inventory.each():
print(business.val())

Or you go iterate it, which is really inefficient to request N items from Firebase for N children.

inventorydb = db.child("Inventories")
for businessid in inventorydb.shallow().get().each():
productdb = inventory.child(businessid)
# print the ids
print([id for id in productdb.shallow().get()])

How can I iterate through children of multiple push keys in Firebase Realtime Database?

To iterate through the children try this:

 DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Lectures").child("Saturday,March 03");

reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String batchname=datas.child("batch_name").getValue().toString();
//etc
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});

the for(DataSnapshot datas: dataSnapshot.getChildren()) will let you iterate inside the push keys.

dataSnapshot.getChildren() will give you the direct children, which are the push keys in this case. Then using the for loop you will be able to access the data inside these keys

Is it possible to iterate through unique children with different values in Firebase Database?

Remove addListenerForSingleValueEvent from child("XRA") and set addListenerForSingleValueEvent on child("Area 71")

Then run a nested loop.

Note : The time complexity is O(n^2)

FirebaseDatabase.getInstance().getReference()
.child("Drawings").child("Area 71").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

for (DataSnapshot parentDS : dataSnapshot.getChildren()) {

for (DataSnapshot ds : parentDS.getChildren()) {
key = ds.getKey();
Current_Version = ds.child("Current Version").getValue().toString();
Previous_Version = ds.child("Previous Version").getValue().toString();
}
}

}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage());
}
});


Related Topics



Leave a reply



Submit