簡體   English   中英

將對象從類傳遞給活動

[英]Pass object from a Class to Activity

我想將來自onSuccess方法的ThreeHourForecast 對象發送回調用它的活動。 我想要這個問題的干凈和最佳解決方案。 這是我的代碼。

天氣預報處理程序類:

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.
}

嘗試在您的函數類型參數中添加一個函數。 喜歡,

天氣預報處理程序類:

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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM