I have Activity A, which displays a list of items that are loaded asynchronously from a web service. This list is stored in a ViewModel. When you select one of those items Activity B will open up with details of the selected item. Activity B is a child Activity of Activity A. Pressing the back button will then go back to Activity A...however, at this point Activity A is destroyed and a new ViewModel is created which calls the web service again.
This isn't similar to the other issues I have seen where the device is rotated while Activity B is in the foreground. The onDestroy method of Activity A is not called when the item is selected and Activity B is displayed...but it is called when the back button is pressed.
I don't want the ViewModel to refresh the data every time the user goes back to Activity A...any idea what could be causing this?
Relevant Manifest info:
<activity android:name=".ActivityA" />
<activity
android:name=".ActivityB"
android:label="@string/title_b"
android:parentActivityName=".ActivityA" />
Activity A:
class ActivityA : AppCompatActivity() {
private lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.a_activity)
mainViewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
...
Not sure what other code would help to diagnose the problem....
You need to remove android:parentActivityName=".ActivityA"
in your manifest. As stated in official documentation:
The system reads this attribute to determine which activity should be started when the user presses the Up button in the action bar.
Therefore, when you return to the previous activity, new ViewModel
is created.