【问题标题】:Adding object to ArrayList将对象添加到 ArrayList
【发布时间】: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.addRescueAdapter adapter = new RescueAdapter(getActivity(), rescueList); 之前添加打印语句以查看发生了什么。
  • 您在调试代码时是否在for 循环中放置了断点,以确保它正在执行?还是日志语句?
  • 你是在调试模式下运行的吗?
  • 我使用函数 isEmpty() 在日志为空时打印。它奏效了。此外,片段中没有显示任何内容,因为适配器正在被提供一个空数组列表

标签: java android firebase arraylist


【解决方案1】:

您得到null,因为您在onDataChange() 之外声明了rescueList ArrayList。这是由于此方法的异步行为而发生的。这意味着将这些对象添加到 ArrayList 的语句在调用 onDataChange() 方法之前执行。要解决这个问题,您需要在onDataChange() 中声明并使用ArrayList。注意不要在 for 循环中添加。

如果您想在该方法之外使用这些值,我建议您从post 中阅读我的答案。

【讨论】:

  • 我正在使用 notifyDataSetChanged() 但它在更新或初始化时相当慢。有更好的方法吗?
  • 你可以看看FirebaseUI。一切都是实时发生的。
猜你喜欢
  • 1970-01-01
  • 2011-12-24
  • 2016-09-26
  • 1970-01-01
  • 2016-08-10
  • 2021-05-26
  • 2019-02-18
  • 2014-01-19
相关资源
最近更新 更多