简体   繁体   中英

Realm new changes?

I have somes problems with update realm

That is my Class

public class Cliente extends RealmObject {
@PrimaryKey
    private long id;
    @Required
    private String nombre;
    private String apellido;
    private String imagen;
    private boolean habilitado;
    private RealmList<Obra> obras;

And have this code only do insert

Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        Cliente cliente = realm.createObject(Cliente.class);
        cliente.setId(1); 
        cliente.setNombre("Desconocido");
        cliente.setApellido("-");
        cliente.setHabilitado(true);
        realm.copyFromRealm(cliente);
        realm.commitTransaction();
        realm.close();

ok y have problems, but ever working this way with realm and android

Caused by: io.realm.exceptions.RealmException: 'Cliente' has a primary key, use 'createObject(Class<E>, Object)' instead.
   at io.realm.Realm.createObjectInternal(Realm.java:820)
   at io.realm.Realm.createObject(Realm.java:801)
   at app.obraresuelta.model.Cliente.insertUsuarioDefault(Cliente.java:38)
   at app.obraresuelta.PrincipalActivity.onCreate(PrincipalActivity.java:31)
   at android.app.Activity.performCreate(Activity.java:6289)

Look at the message:

'Cliente' has a primary key, use 'createObject(Class, Object)' instead.

So it says you should use realm.createObject(Cliente.class, id); instead.

    Realm realm = Realm.getDefaultInstance();
    realm.executeTransaction(new Realm.Transaction() {
       @Override
       public void execute(Realm realm) {
           Cliente cliente = realm.createObject(Cliente.class, 1);
           cliente.setNombre("Desconocido");
           cliente.setApellido("-");
           cliente.setHabilitado(true);
       }
    });
    realm.close();

You should create the object as a normal Java object, set its properties, and then create the realm object.

You can use the copyToRealm function.

https://realm.io/docs/java/latest/#primary-keys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM