skip to Main Content

how can I save the main activity context in a variable to use it in a function of another class? is there a specific method i can use?

I have a class that contains the functions that I would like to use in my main_activity, one of the functions, within the routePath function, which I report below (line 2), requires that the context be passed as a parameter to draw the path on the map, that I would like to know is how can I pass the context when the function is called in the main_activity.
I thought it was possible to save the main activity context in a variable and then retrieve it in the second class.
I can share the whole code if needed.

fun routePath(p1Latit: Double, p1Laong: Double, p2Latit: Double, p2Laong: Double){
        println("inizio")
        val roadManager: RoadManager = OSRMRoadManager(context, "lolloMaps")
        OSRMRoadManager.MEAN_BY_FOOT
        println("passo1 - creoArrayList")
        val waypoints = arrayListOf<GeoPoint>()
        println("passo2 - CreoPuntiEAggiungoInArrayList")
        val startPoint: GeoPoint = GeoPoint(p1Latit, p1Laong) //43.12628, 12.04705
        waypoints.add(startPoint)
        val endPoint: GeoPoint = GeoPoint(p2Latit, p2Laong) //43.12124, 11.97211
        waypoints.add(endPoint)
        println("passo3 - CreoStrada")
        road = roadManager.getRoad(waypoints)
        if (road.mStatus != Road.STATUS_OK){
            Toast.makeText(context, "Errore nel caricamento di road - status = " + road.mStatus, Toast.LENGTH_SHORT).show()
        }
        println("passo4 - CreoPolilinea")
        val roadOverlay: Polyline = RoadManager.buildRoadOverlay(road)
        println("passo5 - AggiungoPolilineaAllaMappa")
        mapView.overlays.add(roadOverlay)
        mapView.invalidate()

I think i should correct the last two lines as well as mapView has been declared in main_Activity, is that right?

2

Answers


  1. Chosen as BEST ANSWER

    I solved it by passing to the class that contains the function both the context and the mapView as constructor parameters


  2. You can use

    Context context = MainActivity.this;    
    

    then pass that context to the method you require.

    like this recyclerViewAdapter here (no need to say you could pass that MainActivity.this directly instead of putting it inside the context variable):

    adapter = new MyRecyclerViewAdapter(context, toDoList);    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search