How to iterate over a DataSnapshot?

Viewed 7013

I'm trying to iterate over the children of the contacts node. enter image description here.

However my ListArray contacts only partially populates. The first two entries populate the array as expected (output from Logcat) but the 3rd entry fails to populate the array. Here is the MainActivity.java:

public class MainActivity extends AppCompatActivity {
TextView stringTextView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    stringTextView = (TextView)findViewById(R.id.textView2);

    FirebaseDatabase firebaseDatabase= FirebaseDatabase.getInstance().getInstance();
    DatabaseReference dbRef= firebaseDatabase.getReference("County/Dublin");

    dbRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            DataSnapshot contactSnapshot = dataSnapshot.child("contacts");
            Iterable<DataSnapshot> contactChildren = contactSnapshot.getChildren();
            ArrayList<Contact> contacts= new ArrayList<>();

            for (DataSnapshot contact : contactChildren) {
                Contact c = contact.getValue(Contact.class);
                Log.d("contact:: ", c.name + " " + c.number);
                contacts.add(c);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
}
}

And the model class Contact.java:

public class Contact {
public String name;
public String number;

public Contact() {
}


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

Why is my ListArray not completely populating?

UPDATE

Here is what I've done with the suggested code example:

@Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<String> names= new ArrayList<>();
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                String name = ds.child("name").getValue(String.class);
                names.add(name);
                String number = ds.child("number").getValue(String.class);
                Log.d("TAG", name);
            }
            for(int i=0; i < names.size(); i++){

                stringTextView.setText(stringTextView.getText() + names
                        .get(i) + " , ");
            }
        }

Array still not populating and no display to the screen.

2 Answers

Contact number 3 doesn't have quotes "" making it a number rather than a string. If you add quotes back it should fix the issue.

Related