我有Activity1,其中在RecyclerView中以LiveData的形式显示Room数据库条目,而Activity2中,有用于添加和更新新条目的必要字段。
我想知道哪种合适的架构来构建这种情况,其中Activity2具有两个角色(创建和更新)。我的方法似乎可行,但我不知道它是否正确。
我目前的做法是:
在Activity1中,当我触发更新操作时,我将单击的数据与操作字符串一起发送:
Intent intent = new Intent(MainActivity.this, AddNoteActivity.class);
intent.setAction(ACTION_UPDATE);
intent.putExtra(AddNoteActivity.EXTRA_ID, note.getId());
intent.putExtra(AddNoteActivity.EXTRA_TITLE, note.getTitle());
intent.putExtra(AddNoteActivity.EXTRA_DESCRIPTION, note.getDescription());
intent.putExtra(AddNoteActivity.EXTRA_PRIORITY, note.getPriority());
startActivityForResult(intent, REQUEST_CODE_UPDATE_NOTE);
反之亦然,添加操作会触发以下代码:
Intent intent = new Intent(MainActivity.this, AddNoteActivity.class);
intent.setAction(ACTION_ADD);
startActivityForResult(intent, REQUEST_CODE_ADD_NOTE);
在Activity2中,我检查操作字符串并在必要时填写输入字段:
Intent intent = getIntent();
if (MainActivity.ACTION_UPDATE.equals(intent.getAction())) {
setTitle("Update Note");
editTextTitle.setText(intent.getStringExtra(EXTRA_TITLE));
editTextDescription.setText(intent.getStringExtra(EXTRA_DESCRIPTION));
numberPickerPriority.setValue(intent.getIntExtra(EXTRA_PRIORITY, 1));
} else if (MainActivity.ACTION_ADD.equals(intent.getAction())) {
setTitle("Add Note");
}
在两种情况下,Activity2中的保存按钮都执行相同的操作,它将新条目(Note对象)发送回Activity1。 Id是自动递增的主键。我使用-1作为默认值,因此如果我触发没有ID的添加操作,则会收到此值。这样,我想避免更新条目而不是添加条目。
private void saveNote() {
String title = editTextTitle.getText().toString();
String description = editTextDescription.getText().toString();
int priority = numberPickerPriority.getValue();
if (title.trim().isEmpty() || description.trim().isEmpty()) {
Toast.makeText(this, "Please insert a title and description", Toast.LENGTH_SHORT).show();
return;
}
int id = getIntent().getIntExtra(EXTRA_ID, -1);
Intent replyIntent = new Intent();
replyIntent.putExtra(EXTRA_ID, id);
replyIntent.putExtra(EXTRA_TITLE, title);
replyIntent.putExtra(EXTRA_DESCRIPTION, description);
replyIntent.putExtra(EXTRA_PRIORITY, priority);
setResult(RESULT_OK, replyIntent);
finish();
}
然后在Activity1中,检查收到的结果,然后添加或更新条目:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
int id = data.getIntExtra(AddNoteActivity.EXTRA_ID, -1);
String title = data.getStringExtra(AddNoteActivity.EXTRA_TITLE);
String description = data.getStringExtra(AddNoteActivity.EXTRA_DESCRIPTION);
int priority = data.getIntExtra(AddNoteActivity.EXTRA_PRIORITY, 1);
switch (requestCode) {
case REQUEST_CODE_ADD_NOTE:
addNote(title, description, priority);
Toast.makeText(this, "Note added", Toast.LENGTH_SHORT).show();
break;
case REQUEST_CODE_UPDATE_NOTE:
updateNote(id, title, description, priority);
Toast.makeText(this, "Note updated", Toast.LENGTH_SHORT).show();
}
}
}