RealmList is crazy

183 Views Asked by At

I use RealmList for android database. I read it 's documents.

 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;....}

and:

public class VG extends RealmObject {

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

When i save new M_P object and new VG ,all new VGs replace to all Previous M_P! please help me!

My code is:

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: Projects. VG: vehicle .

When I save new M_P object with new VG list, new VGs replace to all Previous M_P!

1

There are 1 best solutions below

0
On

That's because your new VG's ID is as same as previus VGs. You need to change your ID pattern. You can't have two objects with same PrimaryKey/ID.