5

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();
    }
}

Source: https://github.com/googlecodelabs/android-room-with-a-view/blob/master/app/src/main/java/com/example/android/roomwordssample/MainActivity.java

Florian Walther
  • 6,237
  • 5
  • 46
  • 104
  • post how u sending response from NewWordActivity back like set result or something! – Shishram Sep 29 '18 at 10:34
  • Because, Google suggests that avoid using Single `ViewModel` due to lifecycle pitfalls to activity, that's why they avoid to use same instance `ViewModel` in second activity & pass data to first activity instead. – Jeel Vankhede Sep 29 '18 at 10:39
  • But the second activity could just use the `ViewModelProviders.of` method to get it's own ViewModel instance` – Florian Walther Sep 29 '18 at 10:41
  • IMHO, Google has no monopoly on the truth. They make bogus decisions too. – beroal Dec 25 '18 at 16:48
  • Because they don't want to create two instances of WordViewModel for two activities. If they use two fragments then yes we can do like what you suggest above, getting the viewModel instance and saving your data. – Khoa Tran Apr 24 '19 at 03:35

1 Answers1

0

Looking at the NewWordActivity class it's very simple and doesn't require its own ViewModel. My guess is that it's to avoid the need to create one for the single purpose of inserting an entry into the database, giving that responsibility to the MainActivity.

Ivan Wooll
  • 4,145
  • 3
  • 23
  • 34