Firebase with Realm. De-serializing POJO class

前端 未结 2 1219
难免孤独
难免孤独 2020-12-12 04:36

I have data in my firebase DB, everything works fine until I try to De-serialize the data.

Error: argument 1 has type io.realm.RealmList, got java.util.Array

相关标签:
2条回答
  • 2020-12-12 04:48

    Firebase won't work with classes that do not have default constructor or private variables i.e no public getter/setter.

    A easier solution in your case would be to make a middleware class that is the same pojo just not extending RealmObject. Next initialise your RealmObject subclass using the values of the pojo.

    Pseudo code

    class SimplePojoPlaylist  {
         public String variable;
    }
    
    class Playlist extends RealmObject {
         public String variable;
    }
    

    Then first cast into SimplePojoPlaylist

        for (DataSnapshot child : dataSnapshot.getChildren()) {
             SimplePojoPlaylist receivedPlaylist = child.getValue(SimplePojoPlaylist.class);
             Playlist playList = new Playlist();
             playList.variable = receivedPlaylist.variable;
        }
    
    0 讨论(0)
  • 2020-12-12 05:05

    RealmList is not a supported type for deserialization. Your database checks its structure and deduces that tracks should be an ArrayList. Then, when it tries to convert it, it finds that the types do not match.

    Check this link from the docs:

    Also, it is a good practice to make your objects immutable to avoid unwanted access and/or modifications.

    Creating an empty object from scratch and then calling setter methods to define its state is not a very good pattern, because it can create a situation where an object is accessed before when its state is "broken".

    If you need to create an object that is flexible, has a few mandatory fields and some optional, consider using the Builder pattern, although to do it you'd have to redesign your model.

    wikipedia - Builder

    If you don't need/want to use a builder, my advice is:

    1) Make the empty constructor private and create another public one that requires all the fields.

    2) Change your tracks field to be of type "List". Then, if you need the object to return a RealmList create another getter method such as tracksAsRealmList() that makes a RealmList out of the member list and returns it.

    3) Make sure that the "Track" model has an empty private constructor, a public one with all of its parameters and that all of its fields are supported by firebase deserialization.

    4) Unless strictly necessary, make your object fields private and set its value through a setter method.

    I hope this helps you.

    0 讨论(0)
提交回复
热议问题