Yan Zhuang
Yan Zhuang

Reputation: 486

Save Fragment data when switch to another fragment using Navigation

I just started with my first Android project. My application contains two fragments that are connected with the navigation controller.

As for now, all I have on my first fragment is only two EditText. However, I realize that when I switch to my other fragment and navigate back, the texts entered have been cleared.

So I would like to know what I can do to save the date and restore them when I switch it back

I have already tried saving them in onSaveInstanceState() as suggested by the majority of people, however, it is not working. So I did a little test, turns out the onSaveInstanceState() is not even being called when I switch the fragment. Instead, onDestroy() and onPause() are being called, ones where people don't recommend to save my data

I have also tried to use ViewModel to save the data but it seems that the data saved into the ViewModel is also gone when I switch back to the original Fragment.

So I am not sure what to do? Thanks!

Upvotes: 0

Views: 893

Answers (1)

Inso
Inso

Reputation: 877

You should use ViewModel, create your ViewModel by Activity instead of Fragment, inside your Fragment.onViewCreated() method

val myViewModel = ViewModelProvider(activity as ViewModelStoreOwner).get(MyViewModel::class.java)

Upvotes: 1

Related Questions