用于记录使用Realm1.0遇到的问题,以及解决方法。

1.
目前Realm的Model还没有defaultValue注解 默认都为数据库中的字段 使用@Ignore将其标识为非数据库字段,使用@PrimaryKey标识其为主键,@Index标识其为索引,目前还没有@DefaultValue [1],但是有@Required 标识其默认值不允许为null:If you are creating a new object, it will get the default value for that datatype, e.g. false for boolean and null for Boolean.
2.一个继承于RealmObject的类,其类名就为表名,但目前无法让RealmObject再继承其他类[2][3][4],这样就无法设置包含共有字段的父类,以及包含处理这些共有字段的方法的抽象Dao类。
3.Realm Browser 目前只支持mac,其他平台可以使用Facebook的Stetho-Realm
4.插入数据时无法设置自动增长的id[5]
5.realm数据库查询得到的RealmResults,必须在当前线程使用
像这样的写法就会报下面Realm access from incorrect threa这个错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
new AsyncTask<Void,Void, RealmResults<FundTrans>>(){
@Override
protected RealmResults<FundTrans> doInBackground(Void... params) {
Realm realm = Realm.getDefaultInstance();
RealmQuery<FundTrans> realmQuery = realm.where(FundTrans.class);
realmQuery.equalTo("userRemark", "123");
return realmQuery.findAll();
}

@Override
protected void onPostExecute(RealmResults<FundTrans> fundTranses) {
ToastUtil.showToast(fundTranses.size());
}
}.execute();

java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
at io.realm.BaseRealm.checkIfValid(BaseRealm.java:395)

at io.realm.RealmResults.isLoaded(RealmResults.java:863)
at io.realm.RealmResults.size(RealmResults.java:370)

6.realm会在编译时为我们的实体类生成一个代理类,比如一个继承于RealmObject的TestRealmObject,就会生成一个TestRealmObjectRealmProxy,其中根据setter/getter方法生成对应的代理类的设置访问方法,比如realmGet$_id以及realmSet$_id,随后就会调用这个代理类的相关方法,而不会调用Model类的方法,这就造成了Model类中不能写其他方法。[6]
7.在查询和排序时,忽略了大小写。

参考文献
[1]https://github.com/realm/realm-java/issues/777
[2]https://github.com/realm/realm-java/issues/761
[3]https://github.com/realm/realm-java/issues/2691
[4]https://github.com/realm/realm-java/blob/e36e69bb6887d3427b40f661a80c71b6dfb2548f/realm/realm-annotations-processor/src/main/java/io/realm/processor/ClassMetaData.java#L105
[5]https://github.com/realm/realm-java/issues/469
[6]http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/1203/3743.html