0

I connected my android app to google's realtime database. (This is for school and I'm very, very new at all of this app development stuff.) And I was wondering why my log.d() method outputs it's contents to the logcat in the wrong order. I don't think it's a major issue and I can probably work around it but I'm just curious about why it executes like this or if it's something wrong with my code I have to fix.

Resident Page:

public class ResidentPage extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        ....
        basicReadWrite();
        MethodsFromOtherClass.output();

        return view;
    }

    ...

    public void basicReadWrite(){
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("second message");

        myRef.setValue("Hello again, World!");

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String value = dataSnapshot.getValue(String.class);
                Log.d("ResidentPage", "Value is: " + value);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                Log.w("ResidentPage", "Failed to read value.", error.toException());
            }
        });
    }
}

Methods from other class:

public class MethodsFromOtherClass {
    public static void output(){
        Log.d("ResidentPage", "Called from another class");
    }
}

Logcat:

D/ResidentPage: Called from another class
D/ResidentPage: Value is: Hello again, World!
Dr_Claymore
  • 21
  • 1
  • 9
  • That's normal behavior. Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a callback. You might also be interested in reading this article, [How to read data from Firebase Realtime Database using get()?](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5). – Alex Mamo Feb 06 '22 at 09:12

1 Answers1

1

They aren't happening in the wrong order. Your code is asynchronous. The ValueEventListener is called after the data is gathered on a background thread. So they can happen in any order- it would be a race condition between which one gets called first. (In more practical terms, the "Called from another class" will almost always happen first in the code above because there's little enough code on that thread that it's unlikely the other thread will be scheduled and run before the main thread gets there, but you may see it happen once in a while).

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127