我想在获取数据后更新我的列表,但是当我尝试时,没有任何反应,仍然显示相同的旧数据。我尝试异步获取数据,但同样的问题发生了。 这是代码。
public class myFragment extends ListFragment{
private DatabaseReference database = FirebaseDatabase.getInstance().getReference();
ArrayAdapter<Event> adapter;
List<Event> eventsList = new ArrayList<Event>();
Event[] events = {
new Event(...), //Test data
new Event(...),
new Event(...)
};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false); //Custom view
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new EventsAdapter(getActivity(), events);
setListAdapter(adapter);
database.child("Events").addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot s : dataSnapshot.getChildren()) {
Event event = s.getValue(Event.class);
eventsList.add(event);
//adapter.add(event); crashes the app for some reason
}
events = eventsList.toArray(new Event[eventsList.size()]);
adapter.notifyDataSetChanged();
}
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void onListItemClick(ListView l, View v, int position, long id) {...}
}
我无法在代码中找到错误,我该如何解决?
答案 0 :(得分:0)
要解决此问题,您需要使用ChildEventListener
代替addValueEventListener
。
database.child("Events").addChildEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot s : dataSnapshot.getChildren()) {
Event event = s.getValue(Event.class);
eventsList.add(event);
//adapter.add(event); crashes the app for some reason
}
events = eventsList.toArray(new Event[eventsList.size()]);
adapter.notifyDataSetChanged();
}
public void onCancelled(DatabaseError databaseError) {
}
});
答案 1 :(得分:0)
当您希望修改数据时,请不要使用数组,请使用ArrayLists。