Передать объект из класса в Activity - PullRequest
0 голосов
/ 08 марта 2020

Я хочу отправить threeHourForecast объект из onSuccess метод обратно в активность, из которой он вызывается. Я хочу чистого и лучшего решения этой проблемы. Вот мой код.

Класс обработчика прогноза погоды:

open class WeatherForecastHandler {

open fun getForecast(lat: Double, lng: Double, weatherKey: String){
    val helper = OpenWeatherMapHelper(weatherKey)
    helper.setUnits(Units.METRIC)
    helper.setLang(Lang.ENGLISH)

    helper.getThreeHourForecastByGeoCoordinates(lat, lng, object : ThreeHourForecastCallback {
        override fun onSuccess(threeHourForecast: ThreeHourForecast) {//send this "threeHourForecast" object back to the place from which "getForecast()" method is called.}

        override fun onFailure(throwable: Throwable) {
            Log.d("forecast", throwable.message!!)
        }
    })
}

}

Место вызова:

Класс активности карт:

open class MapsActivity : FragmentActivity(), OnMapReadyCallback{

private lateinit var googleMap: GoogleMap
private lateinit var startPoint: LatLng

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps)

    val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
    mapFragment!!.getMapAsync(this)

    val bundle: Bundle? = intent.getParcelableExtra("bundle")
    startPoint = bundle!!.getParcelable("startPoint")!!
}

override fun onMapReady(map: GoogleMap?) {
    googleMap = map!!
    val weatherHandler = WeatherForecastHandler()
    weatherHandler.getForecast(startPoint.latitude, startPoint.longitude, getString(R.string.key)
//I need object here.
}

1 Ответ

1 голос
/ 08 марта 2020

Попробуйте добавить функцию в свой параметр типа функции. Как,

Класс обработчика прогноза погоды:

open fun getForecast(lat: Double, lng: Double, weatherKey: String, callback: ((result: ThreeHourForecast?) -> Unit)){
    val helper = OpenWeatherMapHelper(weatherKey)
    helper.setUnits(Units.METRIC)
    helper.setLang(Lang.ENGLISH)

    helper.getThreeHourForecastByGeoCoordinates(lat, lng, object : ThreeHourForecastCallback {
        override fun onSuccess(threeHourForecast: ThreeHourForecast) {//send this "threeHourForecast" object back to the place from which "getForecast()" method is called.
         callback(threeHourForecast)
        }

        override fun onFailure(throwable: Throwable) {
         callback(null)
        }
    })
}

Класс активности карт:

override fun onMapReady(map: GoogleMap?) {
    googleMap = map!!
    val weatherHandler = WeatherForecastHandler()
    weatherHandler.getForecast(startPoint.latitude, startPoint.longitude, getString(R.string.key) { result: ThreeHourForecast? ->
 // You can now receive value of 'threeHourForecast'
}
//I need object here.
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...