如何在RealmList中添加元素

时间:2017-02-19 20:22:59

标签: android realm

这是我的RealmObject类

public class VinScannerHistoryModel extends RealmObject {
@Required
private String vinNumber;
@Required
private String userName;
@Required
private String status;

private RealmList<ImagesObject> imagesObjects;


public String getVinNumber() {
    return vinNumber;
}

public void setVinNumber(String vinNumber) {
    this.vinNumber = vinNumber;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public RealmList<ImagesObject> getImagesObjects() {
    return imagesObjects;
}

public void setImagesObjects(RealmList<ImagesObject> imagesObjects) {
    this.imagesObjects = imagesObjects;
}

}

这是一个RealmList类

public class ImagesObject extends RealmObject {
public String getImageName() {
    return imageName;
}

public void setImageName(String imageName) {
    this.imageName = imageName;
}

private String imageName;

} 我尝试在我的表中添加一些元素,但在RealmList中添加了for循环中的最后一个元素。这是我的代码

 ImagesObject imagesObject = mRealm.createObject(ImagesObject.class);
    VinScannerHistoryModel vinScannerHistoryModel = mRealm.createObject(VinScannerHistoryModel.class);
    vinScannerHistoryModel.setVinNumber(vinNumber.getText().toString());
    vinScannerHistoryModel.setStatus(status);

    if(Global.imagePath!=null && Global.imagePath.size()>0)
    {
        for (int i = 0; i < Global.imagePath.size(); i++) {
            imagesObject.setImageName(Global.imagePath.get(i));
            vinScannerHistoryModel.getImagesObjects().add(imagesObject);

        }
    }
    vinScannerHistoryModel.setUserName(vinScannerModel.getName());
    mRealm.commitTransaction();

Global.imagePath是一个String数组,包含两个元素,在RealmLis中添加了两个元素 我怎么能解决我的问题? 谢谢大家

1 个答案:

答案 0 :(得分:2)

请尝试使用以下代码段。

 ImagesObject imagesObject = mRealm.createObject(ImagesObject.class);
RealmList<ImagesObject> imagesObjectList = new RealmList();
VinScannerHistoryModel vinScannerHistoryModel = mRealm.createObject(VinScannerHistoryModel.class);
vinScannerHistoryModel.setVinNumber(vinNumber.getText().toString());
vinScannerHistoryModel.setStatus(status);

if(Global.imagePath!=null && Global.imagePath.size()>0)
{
    for (int i = 0; i < Global.imagePath.size(); i++) {
        imagesObject.setImageName(Global.imagePath.get(i));
        imagesObjectList.add(imagesObject);
    }
}
vinScannerHistoryModel.setImagesObjects(imagesObjectList);
vinScannerHistoryModel.setUserName(vinScannerModel.getName());
mRealm.commitTransaction();