简体   繁体   中英

Arraylist .add is not working inside loop

I am having some sort of problem with the homeContent Arraylist. Have a look at the code...

        ArrayList<String> homeContent=new ArrayList<>(); //its actually a global list but I'm showing inside just show I've declared and initialised it.
        contentDb=FirebaseDatabase.getInstance().getReference().child("home");
        contentDb.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot ds: dataSnapshot.getChildren()){
                    tag=ds.getValue(String.class);
                    homeContent.add(tag);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getActivity(), "Error Connecting to the Server", Toast.LENGTH_SHORT).show();
            }
        });
        for(int i=0;i<homeContent.size();i++){
            Log.i("Entry",homeContent.get(i));
        }

So I used Log.i to track where the problem is and so I found out that the elements are being added in the list but as soon as it comes out of the loop and the valueEventListener function, it's back to having 0 elements in it.

EDIT: Turns out nothing inside that loop is staying permanently

Ok so thanks to Johannes Kuhn, the problem has been solved, actually the for loop was being executed after the event handler was being called so I had to put the loop inside the event handler.

ArrayList<String>   arrayList = null;  
contentDb=FirebaseDatabase.getInstance().getReference().child("home");
    contentDb.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot ds: dataSnapshot.getChildren()){
                tag=ds.getValue(String.class);
                arrayList = new ArrayList<>();
                arrayList.add(tag); // Add into list like this
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(getActivity(), "Error Connecting to the Server", Toast.LENGTH_SHORT).show();
        }
    });

Better you can add that value into list like I have shared above.

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