I'm trying to add objects received from Firebase Database to an ArrayList. However, the list stays empty even after calling the add method. What am I doing wrong? I'm trying to load data from firebase and is display it in a list view. I used log statements to check if the data from firebase is being received and it is. Anybody with suggestions?
public class RescueFragment extends Fragment {
public RescueFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rescue_list, container, false);
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("rescue");
final ArrayList<RescueAnimal> rescueList = new ArrayList<>();
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
String location = (String) messageSnapshot.child("location").getValue();
String appearance = (String) messageSnapshot.child("appearance").getValue();
String photo = (String) messageSnapshot.child("photo").getValue();
String species = (String) messageSnapshot.child("species").getValue();
String problem = (String) messageSnapshot.child("problem").getValue();
rescueList.add(new RescueAnimal(location, appearance, photo, species, problem));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
RescueAdapter adapter = new RescueAdapter(getActivity(), rescueList);
ListView listView = view.findViewById(R.id.rescue_list);
listView.setAdapter(adapter);
return view;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…