Home > Back-end >  ViewModel dont saved after rotation
ViewModel dont saved after rotation

Time:09-01

I create ViewModel class at fragment, but viewModel is not saving after rotation - every time i got new Viewmodel instance. Where is problem?

Acrivity:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        supportFragmentManager.beginTransaction()
            .addToBackStack(null)
            .replace(R.id.main_container, VideoFragment())
            .commit()
    }
}

Fragment:

class VideoFragment: Fragment() {

    lateinit var viewModel: VideoViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        viewModel = ViewModelProvider(this).get(VideoViewModel::class.java)
        return inflater.inflate(R.layout.fragment_video, container, false)
    }
}

ViewModel:

class VideoViewModel: ViewModel() {
    init {
        Log.i("XXX", "$this ")
    }
}

if i will use "requireActivity()" - as ViewModelStoreOwner - viewModel isnt recreate, but its will bound to activity lifecycle.

viewModel = ViewModelProvider(requireActivity()).get(VideoViewModel::class.java)

CodePudding user response:

This is because you are replacing your Fragment on every configuration change when the Activity is recreated. The FragmentManager already retains your Fragment for you. You should commit the transaction only on the initial creation:

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    if (savedInstanceState == null) {
      supportFragmentManager.beginTransaction()
        .addToBackStack(null)
        .replace(R.id.main_container, VideoFragment())
        .commit()
    }
  }
}

CodePudding user response:

Your problem is most likely caused due to the activity being destroyed and then created again after app is rotated.

To fix this you can give your fragment an id/tag when navigating and then when activity is rotated call your supportFragmentManager if there already exists an instance of your old fragment, if it does, navigate to old fragment instance, otherwise create a new instance just like you are doing now.

Wax911 (commented on 9 may 2020) answer to this question: https://github.com/InsertKoinIO/koin/issues/693

He explains the problem with activities and their lifecycle when rotating the screen

  • Related