I'd imagine this question would apply to any application that uses asynchronous calls.
I'm relatively new to all this, and the problem I'm having is with with fetching data from Firebase to my Android application.
There are several classes throughout the application that need to use data from the "users" table in the database, which I obtain as follows:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("users").child("exampleDataFromUsers");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// do something with the snapshot
}
I'd like to create a general purpose class for handling data retrieval from Firebase, something like:
public class FirebaseDataHandler() {
static String getUserReports() {
// get Reports
}
static int getUserAge() {
// get age
}
}
but since it's being retrieved asynchronously, any calls to these methods simply return null. As a result, my code is currently littered with duplicate code.
If anyone has any insight into a better way to achieve this, it would be much appreciated. Thanks.
I believe this question will generate many good answers primarily based on opinions. But I will still post my opinion anyway:
I personally use Firebase with Android Architecture Components, which (from the documentation) is:
This libraries offers 2 classes to make your data lifecycle aware: Live Data and ViewModel. You can find a guide to integrate these 2 libraries on the Firebase Blog: [Part1, Part2, Part3].
To use the library, you need to add the Google repository to your project's build.gradle file:
and then add the dependency on your app's build.gradle file:
So you create a class that extends from LiveData:
And create a ViewModel which will load this user's data:
Finally, in order to get this data in your activities, you just need to call your ViewModel and observe it's LiveData: