Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Firebase's setValue() work for objects in Java?

Tags:

java

firebase

In Firebase's documentation about lists, there is an example where you create a Java object and write that object to a Firebase reference via setValue() like this:

private static class MyObject {

    private String property1;
    private int property2;

    public MyObject(String value1, int value2) {
        this.property1 = value1;
        this.property2 = value2;
    }

    public String getFirstProperty() {
        return property1;
    }

}

private void populateList() {
    Firebase ref = new Firebase("https://MyDemo.firebaseIO-demo.com/myObjects");
    ref.push().setValue(new MyObject("myString", "7"));
}

How does this work internally, i.e. when you have not written a toString() method and so on, what value will be saved to the Firebase reference exactly? And going one step further, will the Firebase client be able to restore the old object from the saved value? How?

Is it necessary to have a private static class so that Firebase can read the fields?

like image 659
caw Avatar asked Aug 20 '13 16:08

caw


1 Answers

The documentation explains how this works:

Set the data at this location to the given value. The native types accepted by this method for the value correspond to the JSON types:

  • Boolean
  • Long
  • Double
  • Map<String, Object>
  • List<Object>

In addition, you can set instances of your own class into this location, provided they satisfy the following constraints:

  1. The class must have a default constructor that takes no arguments
  2. The class must define public getters for the properties to be assigned. Properties without a public getter will be set to their default value when an instance is deserialized

So, you must create getters for all the properties that you want saved. In your example, your firstProperty property will be written, though it won't be possible to read it back because you haven't defined a default constructor.

like image 76
Chris Jester-Young Avatar answered Nov 15 '22 07:11

Chris Jester-Young