问题
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;
回答1:
You are getting null
because you are declaring the rescueList
ArrayList outside the onDataChange()
. This is happening due the asynchronous behaviour of this method. This means that the statement that adds those objects to the ArrayList is executed before onDataChange()
method has been called. To solve this you need to declare and use that ArrayList
inside onDataChange()
. Be careful not to add inside the for loop.
If you want to use those values outside that method, i sugget you readning my answer from this post.
来源:https://stackoverflow.com/questions/44990217/adding-object-to-arraylist