Challenge 2: Play Sound Across Rotation

i moved around the Web for a while to understand why I’m getting these weird errors in the model view like

viewmodel has no zero argument constructor

till i figured out that i should have a ModelViewFactory, I checked the solution that was suggested in this chapter and implemented it.

I created BeatBoxViewModel.kt:

package com.bignerdranch.android.beatbox

import android.content.res.AssetManager
import androidx.lifecycle.ViewModel

class BeatBoxViewModel constructor(val assets: AssetManager): ViewModel() {


    var beatBox = BeatBox(assets)

    override fun onCleared() {
        super.onCleared()
        beatBox.release()
    }

}

also BeatBoxFactoryModel.kt

package com.bignerdranch.android.beatbox

import android.content.res.AssetManager
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

class BeatBoxFactoryModel(val assets: AssetManager) : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return modelClass.getConstructor(AssetManager::class.java).newInstance(assets)
    }
}

then implemented it in MainActivity

class MainActivity : AppCompatActivity() {

   private lateinit var  beatBoxViewModel : BeatBoxViewModel


    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       val factoryModel =  BeatBoxFactoryModel(assets)
        beatBoxViewModel = ViewModelProvider(this, factoryModel).get(BeatBoxViewModel::class.java)

and removed the onDestroy from MainActivity.

Thank you @jpaone i spent hours looking around till i saw your instructions, I was so close to start using Hilt to solve this…

2 Likes