'User'有一个主键,使用'createObject(Class <e>,Object)'代替

时间:2016-12-08 18:21:34

标签: android realm

在下面的Realm示例中,我创建了两个模型。一个叫做Task,另一个叫做User。在Realm的帮助下,我将使用一对一的关系。即。用户“Theo”有一个任务。

所以这是我的模特。

@RealmClass
public class Task implements RealmModel {

public String getId() {
    return id;
}

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

public String getTitle() {
    return title;
}


public void setTitle(String title) {
    this.title = title;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

@PrimaryKey
private String id;
private String title;

public boolean isCompleted() {
    return isCompleted;
}

public void setCompleted(boolean completed) {
    isCompleted = completed;
}

private String description;
private boolean isCompleted;
 }

@RealmClass
public class User implements RealmModel {
@PrimaryKey
private String id;
private String firstName;
private String lastName;
private Task task;

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getId() {
    return id;
}

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

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public Task getTask() {
    return task;
}

public void setTask(Task task) {
    this.task = task;
}

}

在我的主片段中,我插入了虚拟数据。

public class MainFragment extends Fragment {
private Task task;
private Realm realm;
private TextView textContent;
public MainFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_main, container, false);


    return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Handler handler = new Handler();

    final Runnable r = new Runnable() {
        public void run() {
            realm = Realm.getDefaultInstance();

            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {

                    //Create a user if there isn't one
                    if (realm.where(User.class).count() == 0) {
                        User user = realm.createObject(User.class);
                        user.setFirstName("Theo");
                        user.setLastName("Larsen");
                        user.setId(UUID.randomUUID().toString());
                    }
                }


            });


        }
    };

    handler.postDelayed(r, 1000);

    Runnable r1 = new Runnable() {
        @Override
        public void run() {

            final User u = realm.where(User.class).findFirst();


            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {


                    //Create a task
                    Task t = realm.createObject(Task.class);
                    t.setId(UUID.randomUUID().toString());
                    t.setTitle("Take out recycling");
                    t.setDescription("Do it every morning");
                    //set this task to the user.
                    u.setTask(t);

                }


            });

            Log.d("TASK","Task title: " + u.getTask().getTitle());
        }
    };
    handler.postDelayed(r1, 1000);

}

@Override
public void onDestroy() {
    super.onDestroy();
    realm.close();
}
}

然而,我得到了这个例外。

 io.realm.exceptions.RealmException: 'User' 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 theo.testing.realmapp.MainFragment$1$1.execute(MainFragment.java:58)
                  at io.realm.Realm.executeTransaction(Realm.java:1253)
                  at theo.testing.realmapp.MainFragment$1.run(MainFragment.java:52)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

我正在使用该版本。

io.realm:realm-gradle-plugin:2.2.1

如何解决此异常的任何想法?

谢谢,

西奥。

2 个答案:

答案 0 :(得分:30)

呀。执行异常告诉您的操作。

而不是

    User user = realm.createObject(User.class);
            user.setFirstName("Theo");
            user.setLastName("Larsen");
            user.setId(UUID.randomUUID().toString());

待办事项

   User user = realm.createObject(User.class, UUID.randomUUID().toString());
           user.setFirstName("Theo");
           user.setLastName("Larsen");
           //user.setId(UUID.randomUUID().toString());

的原因

自Realm 2.0.0以来,主键是不可变的,这意味着在创建对象后无法修改它们。所以在创建对象时传递它。

答案 1 :(得分:1)

使用

User user = realm.createObject(User.class, primaryKeyValue);

添加主键或使用UUID.randomUUID().toString()

生成