我是Realm数据库解决方案的新手,我想在我的应用程序中使用它,但在读取领域的测试代码后,我的代码不起作用,我的result
返回零记录。
应用
public class EManApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name("EmanClient.db")
.build();
Realm.setDefaultConfiguration(realmConfiguration);
}
}
清单:
<application
android:name=".EManApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
UserAccountInfo型号:
public class UserAccountInfo extends RealmObject {
@PrimaryKey
private String id;
private String userId;
private String name;
private String family;
private String mobileNumber;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
}
MainActivity:
// Defined realm field
private Realm realm;
/*OnCreate*/
realm = Realm.getDefaultInstance();
realm.beginTransaction();
UserAccountInfo userAccountInfo = new UserAccountInfo();
userAccountInfo.setId(UUID.randomUUID().toString());
userAccountInfo.setUserId("1");
userAccountInfo.setName("MyName");
userAccountInfo.setFamily("MyFamily");
userAccountInfo.setMobileNumber("+98746321");
realm.commitTransaction();
RealmResults<UserAccountInfo> results = realm.where(UserAccountInfo.class).findAll();
for (UserAccountInfo u : results) {
Log.e("", u.getId());
}
在上面得到的结果results
变量为零
答案 0 :(得分:4)
您必须使用copyToRealm
添加新领域对象:
realm.beginTransaction();
UserAccountInfo userAccountInfo = new UserAccountInfo();
userAccountInfo.setId(UUID.randomUUID().toString());
userAccountInfo.setUserId("1");
userAccountInfo.setName("MyName");
userAccountInfo.setFamily("MyFamily");
userAccountInfo.setMobileNumber("+98746321");
realm.copyToRealm(userAccountInfo); // add this line
realm.commitTransaction();
答案 1 :(得分:0)
替代@ Fabio的回答
new UserAccountInfo();
应替换为
realm.createObject(UserAccountInfo.class);