How to separate data handling from Activity

  android, android-activity, kotlin, repository, viewmodel

I have a working Activity (TwalksRouteActivity) that accepts a record id (routeID) from a bundle (passed from a Fragment), pulls the associated record from my repository (routesRepository), and passes an associated value/column (routeName) to my UI. This works fine. However, as I understand best practice (I am learning Android development), the call to my Repository should be in a ViewModel, not an Activity. Is this correct? I have tried but failed to do this myself and would really appreciate some help in how to do this please.


class TwalksRouteActivity() : AppCompatActivity()  {

private lateinit var viewModel: RouteViewModel

override fun onCreate(savedInstanceState: Bundle?) {

    //Log.i("CWM","Called ViewModelProvider")
    //viewModel = ViewModelProvider(this).get(

    var bundle: Bundle? = intent.extras
    var routeID = bundle?.getInt("routeID")

    lifecycleScope.launch (Dispatchers.Main) {
        val database = getDatabase(application)
        val routesRepository = RoutesRepository(database)
        val selectedRoute = routesRepository.getRoute(routeID)
        val routeName = selectedRoute.routeName

        Log.d("CWM", routeName.toString())


        val routeName_Text: TextView = findViewById(
        routeName_Text.text = routeName.toString()
        val routeID_Text: TextView = findViewById(
        routeID_Text.text = routeID.toString()


Source: Android Questions