且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从嵌套的onDataChange修改列表

更新时间:2023-11-28 23:47:52

欢迎使用异步数据加载,它总是向您发送消息.与您的想法相反,数据添加到了timeIntervals.它只是在 打印后添加的.

Welcome to asynchronous data loading, which always messages you up. Contrary to what you think, the data is getting added to timeIntervals. It's just being added after you print it.

最简单的方法是添加一些放置良好的日志语句:

The easiest way to see this is by adding some well placed log statements:

Log.d("timeintervals", "Before starting load additional data");
for (int j = 0; j < apptindex.size(); j++) {
    int index = apptindex.get(j);
    long apptnum = apptnumber.get(j);
    String appnumString = Long.toString(apptnum);
    if (daySchedule != null) {
        mApptDatabase = FirebaseDatabase.getInstance().getReference().child("Appointments").child(appnumString);
        mApptDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.d("timeintervals": "Additional data loaded");
                String name = dataSnapshot.child("targetName").getValue().toString();
                timeIntervals.add(name);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException(); // don't ignore errors
            }
        });
    }

}
Log.d("timeintervals", "After starting load additional data");

运行此代码时,输​​出为:

When you run this code the output is:

开始加载其他数据之前

Before starting load additional data

开始加载其他数据后

已加载其他数据

已加载其他数据

...

这可能不是您期望的顺序.但这很好地解释了为什么timeIntervals在打印时为什么不显示其他信息:尚未加载数据.

This is probably not the order you expected. But it explains perfectly why timeIntervals doesn't show the additional information when you print it: the data hasn't been loaded yet.

这是因为Firebase异步从数据库加载数据,并且在加载数据时不会阻止您的应用程序.

This is because Firebase loads data from the database asynchronously and doesn't block your app while it's loading the data.

处理异步数据的典型解决方案是将需要数据的代码移到数据加载后触发的onDataChange中.例如.如果将timeIntervals的日志记录移到onDataChange,它将在每次加载名称之一时记录间隔.

The typical solution for dealing with asynchronous data is to move the code that needs the data into the onDataChange that fires when the data has loaded. E.g. if you move the logging of the timeIntervals into onDataChange it will log the intervals each time it loads one of the names.

要了解更多有关此的信息,我建议阅读以下内容:

To learn a lot more about this, I recommend reading these:

  • Doug's excellent blog post
  • Setting Singleton property value in Firebase Listener
  • ArrayList is showing empty after getting data from firebase database
  • Firebase/Android: Adding retrieved values from Firebase to arraylist returns null pointer exception
  • Value of a global variable is reset after it is initialised in ValueEventListener
  • Android - Load data from Firebase Database in Fragment