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.

TwalksRouteActivity:

class TwalksRouteActivity() : AppCompatActivity()  {

private lateinit var viewModel: RouteViewModel

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

    //Log.i("CWM","Called ViewModelProvider")
    //viewModel = ViewModelProvider(this).get(RouteViewModel::class.java)

    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())

        setContentView(R.layout.route_detail)

        val routeName_Text: TextView = findViewById(R.id.routeName_text)
        routeName_Text.text = routeName.toString()
        val routeID_Text: TextView = findViewById(R.id.routeID)
        routeID_Text.text = routeID.toString()
    }
}

}

Source: Android Questions

LEAVE A COMMENT