Realm 升级数据库,为表添加新的Field遇到的异常记录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010844304/article/details/82876189

在使用Realm数据库管理的时候,需要对一个表添加field。当时是想的是设置默认值就出错了。错误代码如下

if (!schema.hasField("cultureSwitch")) {
            schema.addField("cultureSwitch", Boolean.class).setNullable("cultureSwitch", true);
        }

异常以信息:

java.lang.IllegalStateException: Field is already nullable: cultureSwitch

看字面信息是该field已经是nullable。那我就去掉设置默认值的代码试试

 if (!schema.hasField("cultureSwitch")) {
            schema.addField("cultureSwitch", Boolean.class);
        }

天不遂人愿,又报错了

io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:
- Property ‘SpeechSettingRealmBean.cultureSwitch’ has been made required.

得,现在又是说该field是required.那好嘛,我又接着改

 if (!schema.hasField("cultureSwitch")) {
            schema.addField("cultureSwitch", Boolean.class).setRequired("cultureSwitch", true);
        }

这次终于大功告成了。

后面又再尝试了另外一种方式,如下:

if (!schema.hasField("cultureSwitch")) {
            schema.addField("cultureSwitch", boolean.class);
        }

同样也是可以的,这个就有必要深究了。

查了stackOverFlowd发现:

  • boolean.class : 是可nullable

  • Boolean.class : 是required

备注:realm版本是5.4.0

PS-人的一生可能会遇到很多喜欢的人,但是心疼的只会有一个

猜你喜欢

转载自blog.csdn.net/u010844304/article/details/82876189