【发布时间】:2017-12-12 21:35:15
【问题描述】:
我正在尝试将从 Firebase 数据库接收到的对象添加到 ArrayList。但是,即使调用了 add 方法,列表仍然是空的。我究竟做错了什么?我正在尝试从 firebase 加载数据并将其显示在列表视图中。我使用日志语句来检查是否正在接收来自 firebase 的数据。有人有建议吗?
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;
【问题讨论】:
-
列表在哪里使用?你怎么知道它是空的?
-
您的
onDataChange函数异步执行。因此,您在使用列表后调用 .add 。在rescueList.add和RescueAdapter adapter = new RescueAdapter(getActivity(), rescueList);之前添加打印语句以查看发生了什么。 -
您在调试代码时是否在
for循环中放置了断点,以确保它正在执行?还是日志语句? -
你是在调试模式下运行的吗?
-
我使用函数 isEmpty() 在日志为空时打印。它奏效了。此外,片段中没有显示任何内容,因为适配器正在被提供一个空数组列表
标签: java android firebase arraylist