如何获取最大id值并将数据更新为id?

Pra*_*ran 1 android realm

我在查询最大id值时遇到了问题,并且还希望将数据更新为最大id.

  public void addDataToRealm()
    {
        int key;
        realm.beginTransaction();
        detailsModel = realm.createObject(DetailsModel.class, id);
        detailsModel.setName(name.getText().toString());
        detailsModel.setPlace(place.getText().toString());
        detailsModel.setAddress(address.getText().toString());
        realm.commitTransaction();
        id++;
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我正在递增每个事务的id值.是否有可能从领域数据库中获取最大id值,并需要更新最大id的值.请帮我解决这个问题.

Sha*_*med 6

你可以尝试这样的事情:

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        // Get the current max id in the EntityName table
        Number id = realm.where(EntityName.class).max("id");
        // If id is null, set it to 1, else set increment it by 1
        int nextId = (id == null) ? 1 : id.intValue() + 1;
    }
});
Run Code Online (Sandbox Code Playgroud)