简体   繁体   中英

How to store data retrieved from Firebase in an ArrayList<String> all at once?

I have some data under same reference in the database and I'm trying to store it in a ArrayList<String> .

Here's how:

    mDatabase.child("child").child(uid).addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            if (dataSnapshot.getValue() != null){
               ids.add(dataSnapshot.getValue().toString());
               Log.d("ids", ids.toString());
            } else {
                Toast.makeText(getBaseContext(), "No data!", Toast.LENGTH_SHORT).show();
            }

        }
        ...
        ...
    });

The reference mDatabase.child("child").child(uid)... has 2 keys stored in it and they are getting stored in ids one-by-one like this:

D/ids: [-Kayr_ENTy4QZQKn3Bgx]
D/ids: [-Kayr_ENTy4QZQKn3Bgx, -KaywN_5pTOrB0ooBIC3]

What I want to know is how to make them get added at once in ids and not one-by-one?

UPDATE 1 :-

the data structure is kind of like this:

-app
  -child
    -uid
      -1484967071: -Kayr_ENTy4QZQKn3Bgx
      -1484967222: -KaywN_5pTOrB0ooBIC3

and using valueEventListener() , as suggested by cartant , is resulting in this getting retrieved:

D/ids: [{1484967222=-KaywN_5pTOrB0ooBIC3, 1484967071=-Kayr_ENTy4QZQKn3Bgx}]

though I only want the keys, which are -KaywN_5pTOrB0ooBIC3 and -Kayr_ENTy4QZQKn3Bgx .

If you want the entire snapshot to be delivered to the listener, use either addValueEventListener or addListenerForSingleValueEvent .

If you use addValueEventListener , the listener will be called with the initial snapshot and again if the database changes.

And if you use addListenerForSingleValueEvent , the listener will be called only once with the initial snapshot.

The snapshot received by the listener will include all of the children. To iterate them you would do something like this:

@Override
public void onDataChange(DataSnapshot snapshot) {
    ArrayList<String> ids = new ArrayList<String>();
    for (DataSnapshot childSnapshot: snapshot.getChildren()) {
        ids.add(childSnapshot.getValue().toString());
    }
}

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