не могу вернуть мой пользовательский объект из местоположения - PullRequest
0 голосов
/ 24 февраля 2020

android studio 3.6

фрагмент:

   import android.content.Context
   import android.location.Location
   import com.google.android.gms.location.FusedLocationProviderClient

   fun getNearestGazStation(): GazStation? {
            var nearestGazStation: GazStation? = null
            val client =
                FusedLocationProviderClient(context)
            val location = client.lastLocation
            location.addOnCompleteListener {
                val myLattitude: Double = it.result?.latitude!!
                val myLongitude: Double = it.result?.longitude!!                
                val gazStationList = getGazStationList()
                val gazStationsWithDistnaceList = mutableListOf<Pair<Float, GazStation>>()
                val myLocation = Location("myLocation")

                myLocation.latitude = myLattitude
                myLocation.longitude = myLongitude
                gazStationList.forEach {
                    val locationGazStation = Location("gazStationLocation")
                    locationGazStation.latitude = it.latitude!!
                    locationGazStation.longitude = it.longitude!!
                    val distance = locationGazStation.distanceTo(myLocation)
                    val currentPair = Pair(distance, it)
                    gazStationsWithDistnaceList.add(currentPair)
                }
                gazStationsWithDistnaceList.sortBy { it.first }
                if (!gazStationsWithDistnaceList.isEmpty()) {
                    val findNearestPair = gazStationsWithDistnaceList.first()
                    nearestGazStation = findNearestPair.second
                }
            }
            location.addOnFailureListener {
                Debug.e(TAG, "getNearestGazStation: addOnFailureListener: ex = ${it}")
            }

            return nearestGazStation
        }

используйте вот так (в другом классе):

init {
        profile.value = ProfileService.getProfile()
        generateBarCodeValue()
        nearestGazStation.value = GazStationService.getNearestGazStation()
        Debug.d(TAG, "INIT: find_nearestGazStation: ${nearestGazStation.value}")
}

Но результат find_nearestGazStation = null. Это NULL , потому что я не возвращаю свой пользовательский объект (nearestGazStation из addOnCompleteListener

Как я могу это сделать; |

...