I try to get a List of all my "Example" Pojos from Firebase. My Service Class is a Singelton and in the Constructor I call the method initialize which calls the Method readAll(). So why is "readAll()" not working correctly ? It runns the onDataChange long after the return so it returns null instead of the Pojo List.
Service
public class Service {
private static volatile Service instance = null;
private List<Example> exampleList= new LinkedList<>();
private ExampleDao exampleDao = new ExampleDao();
public void initialize(){
exampleList= exampleDao .readAll();
}
private Service(){
initialize();
}
public static synchronized Service getInstance(){
if(instance==null)
instance = new Service();
return instance;
}
}
DAO
public class ExampleDao implements ExampleDao<Example> {
private FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("example");
private List<Example> pojoList= null;
@Override
public List<Example> readAll() {
// Read from the database
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
pojoList= new LinkedList<>();
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
pojoList.add(postSnapshot.getValue(Example.class));
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
return pojoList;
}
}