In one of the Google Codelabs, Activity1
displays a RecyclerView
and on button click opens Activity2
where a new entry can be added.
Instead of accessing a ViewModel
in Activity2
and adding the entry to the database directly, they send the entry back to Activity1
and insert it there.
What is the reasoning behind this? Why send the data back to Activity1
? Why not call ViewModelProviders.of(this)
in Activity2
and insert the entry in there?
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, NewWordActivity.class);
startActivityForResult(intent, NEW_WORD_ACTIVITY_REQUEST_CODE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
Word word = new Word(data.getStringExtra(NewWordActivity.EXTRA_REPLY));
mWordViewModel.insert(word);
} else {
Toast.makeText(
getApplicationContext(),
R.string.empty_not_saved,
Toast.LENGTH_LONG).show();
}
}