Modifying a list from nested onDataChange

后端 未结 1 1805
遇见更好的自我
遇见更好的自我 2021-01-26 10:38

I am trying to add data (The String name) to the list in the nested onDataChange. In the outer onDataChange, the data is being added to the timeIntervals arraylist. In the neste

相关标签:
1条回答
  • 2021-01-26 11:20

    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

    After starting load additional data

    Additional data loaded

    Additional data loaded

    ...

    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.

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

    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
    0 讨论(0)
提交回复
热议问题