Android中设置主键自动递增

Android中设置主键自动递增

本文介绍了如何在Realm Android中设置主键自动递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的表设置主键自动增量.

I want to set primary key auto increment for my table.

这是我的班级.我已经设置了主键,但我希望它是自动递增主键.

Here is my Class. I have set primary key but I want it to be auto increment primary key.

public class users extends RealmObject {

@PrimaryKey
private int id;
private long icn;
private String name;
private String email;
private String password;
private int phone;

public String getName() {
    return name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public long getIcn() {
    return icn;
}

public void setIcn(long icn) {
    this.icn = icn;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public int getPhone() {
    return phone;
}

public void setPhone(int phone) {
    this.phone = phone;
}

}

预先感谢.

推荐答案

在事务中,您始终可以可靠地访问当前的最大ID,以此为基础,您可以递增该最大ID并将其用作下一个ID的基础./p>

In a transaction, you can always reliably access the current maximum ID, based on which you can increment that and use it as the basis for the next ID.

 realm.executeTransaction(new Realm.Transaction() { // must be in transaction for this to work
     @Override
     public void execute(Realm realm) {
         // increment index
         Number currentIdNum = realm.where(users.class).max(usersFields.ID);
         int nextId;
         if(currentIdNum == null) {
            nextId = 1;
         } else {
            nextId = currentIdNum.intValue() + 1;
         }
         users user = new users(); // unmanaged
         user.setId(nextId);
         //...
         realm.insertOrUpdate(user); // using insert API
     }
 }

这篇关于如何在Realm Android中设置主键自动递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:27