im working with firebase-realtime on android studio java. I have several classes that read and write data from/to Firebase. what is the best way to do it and avoid code duplication ? i try static singelton class called "FirebaseManager" to hold all firebase function. i dont get the result when try to read data, I understood that this is because Firebase works asynchronously. Is there a way around this or a better way to work with firebase in my classes ? Thanks.
public class FirebaseManager {
private static FirebaseManager instance;
private static FirebaseAuth mFirebaseAuth;
private static FirebaseDatabase mFirebaseDatabase;
private FirebaseManager() {
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
}
public static synchronized FirebaseManager getInstance() {
if (instance == null) {
instance = new FirebaseManager();
}
return instance;
}
public FirebaseAuth getFirebaseAuth() {
return mFirebaseAuth;
}
public FirebaseDatabase getFirebaseDatabase() {
return mFirebaseDatabase;
}
public static List<GameScore> getQuizScoresFromFirebase(){
FirebaseUser firebaseUser = mFirebaseAuth.getCurrentUser();
DatabaseReference mDatabaseReference;
List<GameScore> gamescores = new ArrayList<>();
if (firebaseUser != null){
mDatabaseReference = mFirebaseDatabase.getReference("Users/" + firebaseUser.getUid() + "/quizScoreList");
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//checking if QuizScoresList exists in the current firebase user
if (dataSnapshot.exists()){
long size = dataSnapshot.getChildrenCount();
Log.d("MyTag", "dataSnapshot is exists " + "dataSnapshot count: "+ size);
for (DataSnapshot scoreSnapshot : dataSnapshot.getChildren()) {
GameScore gs = scoreSnapshot.getValue(GameScore.class);
Log.d("MyTag","GameScore: "+ gs.toString());
gamescores.add(gs);
// here gamescores look good and filled with data
Log.d("MyTag","gamescores: "+ gamescores.size());
}
} else {
// need to be hundle
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
//Toast.makeText(QuizScore.this, "Error on get scores from Firebase", Toast.LENGTH_SHORT).show();
}
});
}
return gamescores;
}