【问题标题】:RealmList is crazyRealmList 很疯狂
【发布时间】:2018-11-04 21:50:10
【问题描述】:

我将RealmList 用于android 数据库。我阅读了它的文件。

 public class M_P extends RealmObject {
@SerializedName("id")
@Expose
@PrimaryKey
private int id;

@SerializedName("project_name")
@Expose
private String project_name;
@SerializedName("vg")
@Expose
public RealmList<VG> vg;....}

和:

public class VG extends RealmObject {

@SerializedName("id")
@Expose
@PrimaryKey
@Index
private int id;
@SerializedName("name")
@Expose
private String name; ....}

当我保存新的 M_P 对象和新的 VG 时,所有新的 VG 都会替换为所有以前的 M_P! 请帮帮我!

我的代码是:

public class MainActivity extends AppCompatActivity {
Realm realm;
EditText editText1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    realm=Realm.getDefaultInstance();
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
     editText1=findViewById(R.id.editText);
    final EditText etid=findViewById(R.id.et_id);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Number currentMax = realm.where(M_P.class).max("id");
            int nextid = 0;
            if (currentMax != null) {
                nextid = currentMax.intValue() + 1;
            }
            M_P m_p=new M_P();
            Date date=new Date();
            if(etid.getText().toString().equals("New")){
            m_p.setId(nextid);}
            else {
                m_p.setId(Integer.valueOf(etid.getText().toString()));
            }

            m_p.setProject_name("R"+date);
            List<VG> vgs=MakeVG();

            realm.beginTransaction();

            m_p.setVg(new RealmList<>(vgs.toArray(new VG[vgs.size()])));
            realm.copyToRealmOrUpdate(m_p);

            realm.commitTransaction();
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();


            RealmResults<M_P> m_ps=realm.where(M_P.class).findAll();
            List<M_P> allprojects=realm.copyFromRealm(m_ps);

            allprojects.size();
        }
    });


}



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

private List<VG> MakeVG(){
    List<VG> vs=new ArrayList<>();
    for(int i=0;i<10;i++){
        VG v=new VG();
        v.setId(i);
        v.setName(editText1.getText().toString()+i);
        vs.add(v);
    }
    return vs;
}
}

M_P:项目。 VG:车辆。

当我用新的 VG 列表保存新的 M_P 对象时,新的 VG 会替换为 all 以前的 M_P!

【问题讨论】:

    标签: java android realm realm-list


    【解决方案1】:

    那是因为您的新 VG 的 ID 与以前的 VG 相同。您需要更改您的 ID 模式。不能有两个具有相同 PrimaryKey/ID 的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-01
      • 2010-12-12
      • 1970-01-01
      • 2013-06-01
      • 2014-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多