Issue
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!
Solution
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).
Answered By - Gabe Sechan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.