maybe this question little bit easy, but I don't get any idea why we need an empty constructor to passing a data from Firebase. Here is an example for the code:
public class Hero{
String Name, Weapon, Description, Price, Discount, Id;
public Hero() {
}
public Hero(String name, String weapon, String description, String price, String discount, String id) {
Name = name;
Weapon= weapon;
Description = description;
Price= price;
Discount = discount;
Id= id;
}}
then we need a getter and setter for each Menu..
But whats make dizzy is, Why we need an empty Constructor? Is that really necessary?
Can we just make a class without typing an empty constructor? is this will be the same result?
The fields of the class will be filled in using reflection. But you cannot create a "default" object (meaning: with no fields pre-filled) without a constructor. Firebase cannot figure out on its own what your constructor does, so that's why you need an empty constructor: to allow Firebase to create a new instance of the object, which it then proceeds to fill in using reflection.
This is not specific to Firebase: you'll find the empty constructor everywhere where a framework or library fills in an object for you, such as JPA/Hibernate.
Edit: for completeness' sake, as @Lutzi mentioned, once you define your own constructor, the default empty constructor that Java defines is no longer available to you, which is why you need to define it explicitly.
When you create a model class for Firebase, example:
public class Chat {
private String mName;
private String mMessage;
private String mUid;
public Chat() {} // Needed for Firebase
public Chat(String name, String message, String uid) {
mName = name;
mMessage = message;
mUid = uid;
}
public String getName() { return mName; }
public void setName(String name) { mName = name; }
public String getMessage() { return mMessage; }
public void setMessage(String message) { mMessage = message; }
public String getUid() { return mUid; }
public void setUid(String uid) { mUid = uid; }
}
The getters and setters follow the JavaBean naming pattern which allows Firebase to map the data to field names (ex: getName() provides the name field).
The class has an empty constructor, which is required for Firebase's automatic data mapping.
If the class is constructed like the above, Firebase can perform automatic serialization in DatabaseReference#setValue() and automatic deserialization in DataSnapshot#getValue().
more info here:
FirebaseUI README
setValue() Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With