在我扫描数据库中的每个对象之后,在下面的代码中可以毫无问题地解析数据,然后尝试将它们作为字符串添加到片段的列表视图中。最后,仅出现“ HELLO”,并且活动的标题未添加到我的列表视图中。知道为什么吗?我找不到错误。我添加到ArrayList listItems中的所有信息均已正确添加,但未更新到列表视图中,因此我只能看到我一开始添加的HELLO这个词。
public class PastEventFragment extends Fragment {
public PastEventFragment() {
// Required empty public constructor
}
private ListView lvpast;
private ArrayAdapter<String> adapter;
private ArrayList<String> listItems;
private FirebaseDatabase mFirebaseDatabse;
private DatabaseReference mReference;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_past_events, container, false);
lvpast = v.findViewById(R.id.listviewpast);
listItems = new ArrayList<String>();
listItems.add("HELLO");
mFirebaseDatabse = FirebaseDatabase.getInstance();
mReference = mFirebaseDatabse.getReference("Events");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
int year, month, date, hour, minute;
Calendar calendar = Calendar.getInstance();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
year = ds.child("year").getValue(Integer.class);
month = ds.child("month").getValue(Integer.class);
date = ds.child("date").getValue(Integer.class);
hour = ds.child("hour").getValue(Integer.class);
minute = ds.child("minute").getValue(Integer.class);
//testing purposes.
Log.v("YEAR FROM DB", "" + year);
Log.v("CURRENT YEAR", "" + calendar.get(Calendar.YEAR));
Log.v("MONTH FROM DB", "" + (month - 1));
Log.v("CURRENT MONTH", "" + calendar.get(Calendar.MONTH));
String title = ds.child("title").getValue(String.class);
String toAdd = "Event Title: " + title;
listItems.add(toAdd);
adapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
mReference.addListenerForSingleValueEvent(eventListener);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, listItems);
lvpast.setAdapter(adapter);
return v;
}
}