How to deserialize data from Firebase with inheritance in AndroidStudio

1

I'm doing a very simple app to learn how to use FireBase correctly.

My problem comes when I want to deserialize objects that inherit from X classe.

Example:

The AnimalManager class will be the one containing my ArrayList

The classes [Tiger.class, Dog.class and Cat.class] extend from Animal

The problem is that FireBase does not care about inheritance and when I deserialize my class AnimalManager.class all objects are animal so the specific attributes are not loaded it saves them as if they were all Animal. That means that I no longer have dogs or cats or simply animal tigers.

That's the way I suppose FireBase works and saves like this:

So after realizing it I decided to change the way to do it and use: HashMap I thought it works now! But now I have neither dogs nor cats nor Tigers. They're all Object, so even though they're saved better now, it's no use either:

My init method was as follows:

   public void init(){
    this.animals.put("Gatos", new ArrayList<Object>());
    this.animals.put("Perros", new ArrayList<Object>());
    this.animals.put("Tigres", new ArrayList<Object>());
}

So this does not work since they are Object and not Cat, Dog or Tiger

Then I decided to use generics:

public class AnimalManager implements Serializable {

private HashMap<String, ArrayList<? super Animal>> animals = new HashMap<>();

public AnimalManager() {
}

public void init(){
    this.animals.put("Gatos", new ArrayList<>());
    this.animals.put("Perros", new ArrayList<>());
    this.animals.put("Tigres", new ArrayList<>());
}

public HashMap<String, ArrayList<? super Animal>> getAnimals() {
    return animals;
}

public void setAnimals(HashMap<String, ArrayList<? super Animal>> animals) {
    this.animals = animals;
}

public void addAnimal(String key, Animal o){
    //this.animals.get(key).add(g);

    if(o instanceof Gato){
        Gato g = (Gato) o;
        this.animals.get(key).add(g);
    }else if(o instanceof Perro){
        Perro p = (Perro) o;
        this.animals.get(key).add(p);
    }else{
        Tigre t = (Tigre) o;
        this.animals.get(key).add(t);
    }
}

But then FireBase sends me another error! com.google.firebase.database.DatabaseException: Generic wildcard types are not supported

So is there any way to get this? I want to have an Animal ArrayList of my application in the same array but always keeping in mind that they are Cat, Dog or Tiger

Thank you!

    
asked by Vml11 13.04.2018 в 22:37
source

0 answers