如何在Android中使用Realm检查重复数据

时间:2017-08-08 07:09:27

标签: android database duplicates realm realm-mobile-platform

在我的应用程序中,我存储了一些mockdata,以便在应用程序启动时显示。现在我有另一种选择将数据添加到Realm数据库中。但在我的应用程序中,所有重复数据都存储在数据库中。例如,我在setRealmData()方法中有三个数据。在这个方法中,我用相似的信息创建了相同的数据完整检查此数据。但每当我尝试使用simialer名称添加新数据时,它也存储在应用程序中,我实际上并不想要。如何将预装数据复制到Realm中的新数据。

我的活动类是

public class MyColleaguesPage extends AppCompatActivity implements MyColleaguesAdapter.ColleagueListListener{

private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
private Realm colleagueRealm;
private RealmResults<MyColleagueModel> dataResult;
private static final String DIALOG_TAG = "EmployeeDialog";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mycolleagues_layout);

    // Showing and Enabling clicks on the Home/Up button
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
    colleagueRealm = Realm.getDefaultInstance();
    recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);

    setUpRecycler();

    if (!Prefs.with(this).getPreLoad()) {
        setRealmData();
    }
    showAllPersons();
}

private void showAllPersons() {
    dataResult = colleagueRealm.where(MyColleagueModel.class).findAll();
    setAdapter(dataResult);
    adapter.notifyDataSetChanged();
}

private void setAdapter(RealmResults<MyColleagueModel> results) {

    adapter = new MyColleaguesAdapter(this, colleagueRealm.where(MyColleagueModel.class).findAllSortedAsync("id"),this);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}
private void setUpRecycler() {
    // use this setting to improve performance if you know that changes
    // in content do not change the layout size of the RecyclerView
    recyclerView.setHasFixedSize(true);
    // use a linear layout manager since the cards are vertically scrollable
    final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(layoutManager);
}

private void setRealmData(){

    List<MyColleagueModel> colleague = new ArrayList<>();
    MyColleagueModel model = new MyColleagueModel();
    model.setId(1);
    model.setName("Name1");
    model.setCompany("Comapny1");
    model.setTitle("Title1");
    colleague.add(model);
    model = new MyColleagueModel();
    model.setId(2);
    model.setName("Name2");
    model.setCompany("Comapny2");
    model.setTitle("Title1");
    colleague.add(model);
    model = new MyColleagueModel();
    model.setId(2);
    model.setName("Name2");
    model.setCompany("Comapny2");
    model.setTitle("Title1");
    colleague.add(model);
    model = new MyColleagueModel();
    model.setId(3);
    model.setName("Name3");
    model.setCompany("Comapny3");
    model.setTitle("Title3");
    colleague.add(model);


    for (MyColleagueModel realmModel : colleague) {
            // Persist the colleague data
        colleagueRealm.beginTransaction();
        colleagueRealm.copyToRealmOrUpdate(realmModel);
        colleagueRealm.commitTransaction();
    }

    Prefs.with(this).setPreLoad(true);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.recycler_menu, menu);

    final MenuItem item = menu.findItem(R.id.search);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == android.R.id.home) {
        finish();
    }
    //onOptionsItemSelected(MenuItem item) add will open dialog box, which allows user to fill required data
    if (id == R.id.addColleague) {
        showAlertDialog();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void showAlertDialog() {
    EditColleagueFragment dialog = new EditColleagueFragment();
    //dialog.setPositiveButtonClickListener(this);
    dialog.show(getSupportFragmentManager(), DIALOG_TAG);
    //adapter.notifyDataSetChanged();
}

@Override
protected void onDestroy() {
    if (colleagueRealm!= null)
        colleagueRealm.close();
    super.onDestroy();
}

}

我的EditDialog片段类是

public class EditColleagueFragment extends DialogFragment {
private EditText id;
private EditText name;
private EditText role;
private EditText company;
private EditText mobile;
private EditText email;
private EditText department;

private View view;
private LayoutInflater inflater;
private Realm mRealm;

/*public interface onSaveClickListener {
    void onSaved();
}
private onSaveClickListener mSaveClickListener;

public void setPositiveButtonClickListener(onSaveClickListener listener){
    mSaveClickListener=listener;
}*/
public EditColleagueFragment() {

}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    inflater = getActivity().getLayoutInflater();
    view = inflater.inflate(R.layout.edit_my_colleague, null);
    id = (EditText) view.findViewById(R.id.id);
    name = (EditText) view.findViewById(R.id.name);
    role = (EditText) view.findViewById(R.id.role);
    company = (EditText) view.findViewById(R.id.company);
    mobile = (EditText) view.findViewById(R.id.mobile);
    email = (EditText) view.findViewById(R.id.email);
    department= (EditText) view.findViewById(R.id.department);

    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
    dialog.setTitle("Add Colleague");
    dialog.setView(view);
    dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
  {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.cancel();
        }
    });
    dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            savePerson();
        }
    });
    return dialog.create();
}

private void savePerson() {
    mRealm = Realm.getDefaultInstance();
    mRealm.beginTransaction();

    MyColleagueModel model=new MyColleagueModel();
    model.setId(id.getId());
    model.setName(name.getText().toString());
    model.setTitle(role.getText().toString());
    model.setCompany(company.getText().toString());
    model.setMobile(mobile.getText().toString());
    model.setEmail(email.getText().toString());
    model.setDepartment(department.getText().toString());

    mRealm.copyToRealmOrUpdate(model);
    mRealm.commitTransaction();
    mRealm.close();

 }
}

2 个答案:

答案 0 :(得分:0)

使用Realm Mobile Platform避免重复数据的方法是使用主键。

通常,在客户端之间同步数据时会保留所有插入和更新,但通常多个客户端希望插入逻辑上相同的数据。要确保将这些插入折叠为单个对象,可以在模型上使用主键列,通过该列可以在两个客户端上标识对象。如果两个客户端每个都插入一个具有相同主键值的对象,那么这些对象在逻辑上将被视为相同,并且在同步后您将最终只得到一个对象。

您尚未共享模型,但看起来有一个“ID”字段 - 可以作为主键。 : - )

请注意,如果您只进行本地更改(不同步),则主键冲突将导致抛出错误,并且您必须手动处理预先存在的对象的情况。

如果使用主键对您的用例不方便,您始终可以选择等待下载完成,然后手动清理数据库 - 只需确保客户端能够做出关于丢弃哪个对象的相同决定,以免丢掉超过必要的东西。

答案 1 :(得分:0)

尝试使用下面的代码

#