Search code examples
androidmvvmandroid-mvvm

How to implement a BaseActivity in mvvm architecture? Without using dependency Injection


I am currently learning MVVM architecture. I tried to make a BaseActivity class.

My BaseActivity:

abstract class BaseActivity<ViewModel : BaseViewModel, Binding : ViewDataBinding> :
    AppCompatActivity(),
    EventListener {

    lateinit var binding: Binding
    private var viewModel: ViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)

        binding = DataBindingUtil.setContentView(this, layoutid)
        this.viewModel = viewModel ?: getViewModel()
        binding.setVariable(getBindingVariable(), viewModel)
        binding.executePendingBindings()
    }
 
    @get: LayoutRes
    abstract val layoutid: Int

    abstract fun getViewModel(): ViewModel

    abstract fun getBindingVariable(): Int
  
    private fun getViewModelClass(): Class<ViewModel> {
        val type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
        return type as Class<ViewModel>
    }
}

Now I am using this BaseActivity in my SplashActivity:

class SplashActivity : BaseActivity<SplashActivityViewModel, ActivitySplashBinding>() {
    private lateinit var viewModel: SplashScreenViewModel

    override fun onFailure(message: String) {}

    override fun onStarted() {}

    override fun onSuccess() {}

    override fun getViewModel(): SplashActivityViewModel {
        viewModel = ViewModelProvider(this).get(SplashActivityViewModel::class.java)
        return viewModel
    }

    override fun getBindingVariable(): Int {
        return BR.splash_viewmodel
    }

    override val layoutid: Int
        get() = R.layout.activity_splash
    
}

I have used following answer as a reference to implement my BaseActivity.kt: https://stackoverflow.com/questions/55289334/how-to-have-generic-viewmodel-in-baseactivty-class But I am getting a blank white screen while running the app.

Can someone please tell me what is the problem here or how to make this BaseActivity (without using dependency injection)?


Solution

  • you have overridden the wrong onCreate

    override fun onCreate(savedInstanceState: Bundle?) {
    

    I did play around with something like that few years ago, you can find my approach here