使用自动增量ID将项添加到域

时间:2018-01-09 11:52:01

标签: android android-studio android-recyclerview realm recyclerview-layout

我正在尝试将项目添加到领域数据库,同时手动实现自动增量ID,以便删除项目。

这是我试图自动递增

行的id的添加按钮
add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            System.out.println(id);
            realm.beginTransaction();
            UserInfo userInfo=realm.createObject(UserInfo.class);
            if (realm.where(UserInfo.class).endsWith("Id",userInfo.Id).findAll()!=null) {
                id = Integer.parseInt(String.valueOf(realm.where(UserInfo.class).endsWith("Id", userInfo.Id).findAll())) + 1;
            }
            else{
                id=0;
            }
            userInfo.setId(String.valueOf(id));
            userInfo.setUsername(username.getText().toString());
            userInfo.setPassword(password.getText().toString());
            userInfo.setType(dropdown.getSelectedItem().toString());

            realm.commitTransaction();
            Toast.makeText(Add.this,"Username and Password Saved",Toast.LENGTH_LONG).show();
            Intent toMain=new Intent (Add.this,List.class);
            startActivity(toMain);
        }
    });

这是表示领域数据库表的UserInfo类

public class UserInfo extends RealmObject {

String Id;

public String getId() {
    return Id;
}

public void setId(String id) {
    Id = id;
}

String username;
String password;
String type;

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public String getPassword() {
    return password;
}

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

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

}

这是我得到的错误

java.lang.NumberFormatException: For input string: "[UserInfo = [{Id:null},{username:null},{password:null},{type:null}]]"

2 个答案:

答案 0 :(得分:0)

if (realm.where(UserInfo.class).endsWith("Id",userInfo.Id).findAll()!=null) {
        if(userInfo.Id!=null)
        id = Integer.parseInt(String.valueOf(realm.where(UserInfo.class).endsWith("Id", userInfo.Id).findAll())) + 1;
        else
        id=0;
    }
else{
        id=0;
    }

答案 1 :(得分:0)

我认为您应该更新您的领域,您只是将数据设置为pojo但不会在此之后更新领域

 userInfo.setType(dropdown.getSelectedItem().toString())
 realm.insertOrUpdate(userInfo);