I'm quite new to Firebase Realtime database. I'm working on an android app which requires data to be retrieved from Firebase Realtime DB. I've been able to retrieve data using the Firebase listener methods in most occasions but on one occasion, I've found it unable to get a value in the way that I want (I think because of the asynchronous nature).
SCENARIO:-
I have a data structure in Firebase Realtime Database as follows:
For rating:
For users:
I have a separate java class (Suggest.java) that has one simple method to get a list of users (not shown here since it is the basic implementation) and the method defined below to retrieve data from the above ratings node to a list:
public List<String> getMyUnratedPosts(final String currentUserId){
final List<String> currentUserUnratedPosts = new ArrayList<>();
DBRCurrentUnratedList = FirebaseDatabase.getInstance().getReference().child("adRat").child(currentUserId);
DBRCurrentUnratedList.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
AdRat adr = snapshot.getValue(AdRat.class);
int vr = adr.getViewRating();
if(vr < 1) {
currentUserUnratedPosts.add(adr.getAdId());
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return currentUserUnratedPosts;
}
The AdRat class defined above is just a class with attributes (and getters and setters) which matches the database node given above.
I'm creating an instance of this class (Suggest.java) in the onCreate() method of my activity. Then first I'm calling a method in which I'm simply getting a list of users (very similar to above method in which I get the ratings). Then the next line of code in my activity I use a for loop to get each user from the list I got and use that userId for the method shown above. For example, it would be as follows:
Suggest sj = new Suggest();
List<String> users = sj.getUsers();
for (final String mUser: users) {
//Just trying to use the user from above here
List<String> myUnratedItems = sj.getMyUnratedPosts(mUser);
Log.d(TAG, "list contains : " + myUnratedItems.toString());
}
PROBLEM :-
I do not get the intended result from the code when I run this. When I debug it, I will get null for the list of users. I think since the firebase methods are asynchronous they do not give the result exactly at the next line of code (that is the place where I need it) but gives the result a bit later (but then the program has run over the line of code in which I need that data).
MY OVERALL NECESSITY : -
Get the list of users to use it in the next line of code (for the next method).
I've gone through several questions in Stackoverflow in regard to this, but couldn't find an exact answer for this.
Please kindly explain as to why this happens and any workaround for this....
P.S. : - I'm new to stackoverflow, so please bear with me any mistakes done in composing the question. Thanks.