简体   繁体   中英

Iterator.next is not working

im tring to get all value for all children from firebase database but when i run this code below i only get the first child value multi times.

  names=new ArrayList<>();
        rootRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()) {
                    i = i + 1;
                    names.add(dataSnapshot.getChildren().iterator().next().getValue(String.class));
                }
                Toast.makeText(signup.this,""+names,Toast.LENGTH_LONG).show();

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

can i cange the Iterator to a list? i want the simplest way to do it

You're creating a new dataSnapshot.getChildren().iterator() in every iteration of your loop. Try to just use the value of the foreach inside the loop:

for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
  i = i + 1;
  names.add(dataSnapshot1.getValue(String.class));
}

Or if you want to use the iterator, do it like this so it's only created once:

for(Iterator<DataSnapshot> it = dataSnapshot.getChildren().iterator(); it.hasNext(); ){
  i = i + 1;
  names.add(it.next().getValue(String.class));
}

Alternatively you can use a while-loop, which is basically equal to the second piece of code above:

Iterator<DataSnapshot> it = dataSnapshot.getChildren().iterator();
while(it.hasNext()){
  i = i + 1;
  names.add(it.next().getValue(String.class));
}

This might work better for you:

for (DataSnapshot child : dataSnapshot.getChildren()) {
    names.add(child.getValue(String.class));
}
Toast.makeText(signup.this,""+names,Toast.LENGTH_LONG).show();

That form of the loop is iterating through the collection returned by the call to getChildren() .

By calling dataSnapshot.getChildren().iterator().next() inside your loop, you're only ever getting the first element returned by dataSnapshot.getChildren() . Try taking the Iterator outside of the loop:

Iterator<DataSnapshot> it = dataSnapshot.getChildren().iterator();
while (it.hasNext()) {
   String nextValue = it.next().getValue(String.class);

   names.add(nextValue);
}

Edit: Didn't notice you defined that type..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM