How to bypass unique ID and retrieve multiple auto generated child

只谈情不闲聊 提交于 2020-01-17 04:14:06

问题


I want to retrieve multiple child with an auto generated child(Estab_url child). Here is my Code. All i can retrieve is one child and its random

final DatabaseReference establishments = database.getReference("establishments");


  establishments.child(s2).child("Estab_url").addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                if (dataSnapshot.hasChildren()) {
                 //   String value = dataSnapshot.getValue(String.class);
                    String sd = dataSnapshot.getKey();
                    Name.setText(sd);
                }

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

回答1:


If you're looking to read the URL value for each child:

establishments.child(s2).child("Estab_url").addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        String url = dataSnapshot.child("url").getValue(String.class);
        Name.setText(url);
    }

If that is not what you're looking for, please update your question to rephrase the problem.

Update

If you'd like to catch all URLs in a list, you'd set up the list outside of the listener and then add each URL to it as it comes in:

List<String> urls = new LinkedList<String>();
establishments.child(s2).child("Estab_url").addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        String url = dataSnapshot.child("url").getValue(String.class);
        urls.add(url);
        // TODO: do something with the up-to-date list of URLs
    }

But note that you still cannot use the list outside of the listener. Any code that needs the up-to-date content of the list, will need to be called/triggered from within (in this case) onChildAdded.



来源:https://stackoverflow.com/questions/42375899/how-to-bypass-unique-id-and-retrieve-multiple-auto-generated-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!