我在Android上使用Realm数据库,并编写了一个函数来获取自动增量的Id,因为默认情况下它没有实现。当试图列出对象并计算它们时,我得到了这个例外:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.Map.get(java.lang.Object)
at io.realm.RealmQuery.maximumInt(RealmQuery.java:1097)
at mypackage.api.RealmAPI.id(RealmAPI.java:78)' on a null object reference
代码:
public class RealmAPI {
private static Context context;
private static RealmConfiguration realmConfig;
private static RealmAPI instance;
public RealmAPI(Context context) {
this.context = context;
realmConfig = new RealmConfiguration.Builder(context)
.deleteRealmIfMigrationNeeded().build();
}
public static RealmAPI getInstance() {
if (instance == null)
instance = new RealmAPI(context);
return instance;
}
public int id(Class<? extends RealmObject> aClass) {
Realm realm = Realm.getInstance(realmConfig);
Log.d("realm", realm.where(aClass).count()+"");
// exception below
return realm.where(aClass).count() == 0 ? 0 :
(int) realm.where(aClass).maximumInt("id") + 1;
}
}