Home > Enterprise >  Polymorphism in Firebase
Polymorphism in Firebase

Time:10-04

I'm having a little trouble with Firebase. I've structured my data like this:

Class PoJo{
  int field
  String field
  PolyPojo field
}

Class PolyPojo {
  int typeForAll
}

Class PolyType1 {
  int field1
  String field2
}

Class PolyType2 {
  boolean field3
  long field4
}

I have the need for the PolyPojo to be instantiable and if nothing else happens in the code the default constructor for PoJo instantiates a PolyPojo to the PolyPojo field. The issue I am having is I am checking that a PolyType1 class is being instantiated and sent up to firebase. I check firebase and the data is stored correctly. When I try to read the data from my db ref like thus:

ref.child("users").child(user.getUid()).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (!task.isSuccessful()) {
            Log.e("firebase", "Error getting data", task.getException());
        }
        else {
            Log.d("firebase", String.valueOf(task.getResult().getValue()));
            PoJo pojo = task.getResult().getValue(PoJo.class);
            if (pojo != null) {
                this.pojo = pojo;
                onDataLoaded();
            }
        }
    }
});

Everything on the parent class is fine and works correctly except the PolyPojo field, the issue I am having is that the PolyPojo field is being typed as just a PolyPojo and not the correct polymorphed class PolyType1.

Anyone know what I'm doing wrong?

For more context, all of the classes are correctly (AFAIK) implementing parcelable and serialization/deserialization from deconstruction and reconstruction of activities is working as expected, though I don't believe using the getValue(Class.class) works off those functions.

CodePudding user response:

Firebase doesn't store any type information about the object you pass to it. If you expect to get a PolyPojo from the database, you'll need to explicitly say so in the call to getValue:

task.getResult().getValue(PolyPoJo.class)

Since Firebase doesn't store such information, this typically means that you also need to store the type information yourself - so add an additional property to the database that signals the data is for a PolyPojo object.

  • Related