Search code examples
javaandroidlistintrealm

error: Type 'int[]' of field is not supported | how to add integer list to Realm?


I'm creating Realm Object with Realm Database. I want to declare List integer to my object. This is my class:

@PrimaryKey
private int id;
private String name;
private String image;
private String thumbnail;
private String message;
private int[] genre;
private int[] method;

When i compile it, i get error at

Error:(12, 8) error: Type 'int[]' of field 'genre' is not supported

What to do with this? I tried with List<Integer> but no luck.

Then i realized that Integer object doesn't extends RealmObject so I cannot use it.

Any idea will help. Thanks.


Solution

  • What to do with this? I tried with List but no luck. Then i realized that Integer object doesn't extends RealmObject so I cannot use it.

    Well, you can use the RealmList for this purpose :

    @PrimaryKey
    private int id;
    private String name;
    private String image;
    private String thumbnail;
    private String message;
    private RealmList<RealmInt> genre;
    private RealmList<RealmInt> method;
    

    RealmInt.java

    public class RealmInt extends RealmObject {
        private int val;
    
        public RealmInt() {
        }
    
        public RealmInt(int val) {
            this.val = val;
        }
    
        // Getters and setters
    }
    

    And this is how you'd add elements to the RealmList:

    RealmList<RealmInt> list = new RealmList<RealmInt>();
    in.beginArray();
    while (in.hasNext()) {
        list.add(new RealmInt(in.nextInt()));
    }
    

    And then you can call the setter of the main RealmObject class and pass the list.

    [ SOURCE ]