I am a core Java guy and a bit new to android. I want to follow the same old class design pattern what I do in my Java application:
Considering a standard crud. A Base DAO which will create on single instance of Database (FirebaseDatabase):
FirebaseDatabase database = FirebaseDatabase.getInstance();
A EntityDAO extends BaseDAO uses the database from BaseDAO and gets reference says Product
:
DatabaseReference productRef = database.getRef("products");
productRef.addValueEventListener(...)
There will be a service class which calls the DAO to access the product data.
How do I modify this pattern to handle the async onDataChanged
?
Sample Code:
//ProductDAO.java
public class ProductDAO {
private FirebaseDatabase fb;
private DatabaseReference productRef;
private Product product;
public ProductDAO(){
fb = FirebaseDatabase.getInstance(); //Already linked in the firebase console
productRef = fb.getDatabaseReference("product");
productRef.addValueEventListener( new ValueEventListener(){
onDataChange(..){
Log.i("AZ", dataSnapshot.getValue().toString());
}
});
}
public ProductDAO getInstance(){
return new ProductDAO();
}
public Product getProduct(){
return Product; //This will be null because the listener is not completed when the getInstance loads;
}
}
//ProductService.java
public class ProductService{
private ProductDAO productDAO = ProductDAO.getInstance();
public Product getProducts(){
return productDAO.getProducts(); //This will always return null
}
}