【发布时间】:2021-06-04 07:39:29
【问题描述】:
我有一个问题: 我有一个活动和一个班级。该类通过网络发出请求并返回结果。 Activity有这个类的一个对象,通过这个对象Activity访问这个类并返回信息。我附上有关该主题的代码:
class MainActivity : AppCompatActivity() {
private lateinit var dataProcessing : DataProcessing
override fun onCreate(savedInstanceState: Bundle?) {
dataProcessing = DataProcessing()
private fun showData(){
// other code
dataList = dataProcessing.sendRequest(townName) // return null!
val wheather = dataList.get("nameTown")
Log.d("Egor","two $wheather")
val tem = dataList.get("temperature")
Log.d("Egor","three $tem")
dataShow(wheather, tem)
class DataProcessing {
private val retrofitImpl: RetrofitImpl = RetrofitImpl()
private val mainActivity : MainActivity = MainActivity()
lateinit var listString : MutableMap<String, String>
var map: Map<String,String> = mapOf()
internal fun getInfoToMainActivity(townName:String): Map<String, String>{
sendRequest(townName)
return listString
}
internal fun sendRequest(townName:String) : Map<String,String>{
retrofitImpl.getRequest().showWeather(townName).enqueue(object : Callback<DateWeather> {
var objectMainActivity = mainActivity ?: MainActivity()
var listString= mutableMapOf<String, String>()
override fun onResponse(call: retrofit2.Call<DateWeather>, response: Response<DateWeather>) {
val dateWeather:DateWeather? = response.body()
if (response.isSuccessful && dateWeather != null) {
val nameTown = dateWeather.weather.get(0).toString()
Log.d("Egor","nametown" + nameTown)
val size = nameTown.length - 1
listString.apply {
put("nameTown", nameTown.subSequence(13, size).toString())
put("temperature", dateWeather.main.temp!!.toInt().toString())
Log.d("Egor","one ${listString.get("nameTown")}")
}
map = listString.toMap()
} else
Toast.makeText(MainActivity(), "Error", Toast.LENGTH_LONG).show()
}
override fun onFailure(call: Call<DateWeather>, t: Throwable) {
Toast.makeText(MainActivity(), "network error", Toast.LENGTH_LONG).show()
}
})
Log.d("Egor","step before returning the mep $map")
return listString;
}
}
按时间,日志显示如下:
2021-05-30 02:59:31.208 19871-19871/com.example.wheatherprog D/Egor:step before returning the map
2021-05-30 02:59:31.208 19871-19871/com.example.wheatherprog D/Egor: two null
2021-05-30 02:59:31.208 19871-19871/com.example.wheatherprog D/Egor: three null
2021-05-30 02:59:31.355 19871-19871/com.example.wheatherprog D/Egor: nametownWeather(main=Clear)
2021-05-30 02:59:31.355 19871-19871/com.example.wheatherprog D/Egor: one Clear
onResponse() 异步工作,因此在程序将 listString 传递给活动后,数据将写入 Map ( var listString)。结果,我没有数据,程序是空的。直接调用 onResponse() 是没有意义的,因为它不会返回任何东西。 我不想将数据处理中的代码移动到 activiti。但是如何从 Activity 向 DataProcessing 发出请求并从那里返回数据?
我真的希望得到帮助。
【问题讨论】:
-
我对你的代码很困惑。你能把它们修好,把它放好吗?