In one of the fragments of my app I am trying to get the coordinates of my current position but when I try to save them in a variable this is not possible because I get a reference to a null object. I think the reason is a matter of time, my position is not initialized before being saved in the variable. How can I make sure this happens before saving it in the variable? what am I doing wrong?
This is the function i tried to get it coordinates
fun routePathPosi(){
myLocationNewOverlay = MyLocationNewOverlay(GpsMyLocationProvider(context), mapView)
myLocationNewOverlay.enableMyLocation()
myLocationNewOverlay.isDrawAccuracyEnabled = true
val a: Double = myLocationNewOverlay.myLocation.latitude
val b: Double = myLocationNewOverlay.myLocation.longitude
println("my location is : $a and $b")
}
this is my error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: uk.co.lorenzopulcinelli.navigationdrawer, PID: 32684
java.lang.NullPointerException: Attempt to invoke virtual method 'double org.osmdroid.util.GeoPoint.getLatitude()' on a null object reference
at uk.co.lorenzopulcinelli.navigationdrawer.NavFun.routePathPosi(NavFun.kt:90)
at uk.co.lorenzopulcinelli.navigationdrawer.CreatePathFragment.onCreateView$lambda-3(CreatePathFragment.kt:98)
at uk.co.lorenzopulcinelli.navigationdrawer.CreatePathFragment.$r8$lambda$wqVLFXUeXU7qjx0UlbTvNIoGrJQ(Unknown Source:0)
at uk.co.lorenzopulcinelli.navigationdrawer.CreatePathFragment$$ExternalSyntheticLambda2.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7185)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1194)
at android.view.View.performClickInternal(View.java:7162)
at android.view.View.access$3500(View.java:819)
at android.view.View$PerformClick.run(View.java:27678)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7590)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
I/Process: Sending signal. PID: 32684 SIG: 9