领域数据库 - 尝试获取最大ID时的NullPointer

时间:2016-05-07 15:34:03

标签: java android nullpointerexception realm

我在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;
}
}

0 个答案:

没有答案