You need to enable JavaScript to run this app. 使用Retrofit发起异步网络请求时无法正确返回数据如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

使用Retrofit发起异步网络请求时无法正确返回数据如何解决?

问题原因说明
  • 空值问题核心是Retrofit的enqueue方法是异步执行,调用后不会等待网络请求返回就会直接执行后续代码,所以同步返回的listString还没被赋值自然是空的
  • 原有代码存在严重错误:DataProcessing中直接通过MainActivity()实例化Activity完全不符合Android组件规范,自行new的Activity实例不是系统创建的运行实例,既无法正常展示Toast,还会导致内存泄漏
解决方案1:接口回调(通用兼容方案)

通过自定义回调接口将异步结果回传给Activity,不需要把业务逻辑移到Activity中:

步骤1:定义回调接口

interface WeatherRequestCallback {
    fun onSuccess(weatherData: Map<String, String>)
    fun onError(errorMsg: String)
}

步骤2:修改DataProcessing类

删除内部的MainActivity实例,调整请求方法接收回调参数:

class DataProcessing {
    private val retrofitImpl: RetrofitImpl = RetrofitImpl()

    internal fun sendRequest(townName:String, callback: WeatherRequestCallback) {
        retrofitImpl.getRequest().showWeather(townName).enqueue(object : Callback<DateWeather> {
            override fun onResponse(call: retrofit2.Call<DateWeather>, response: Response<DateWeather>) {
                val dateWeather:DateWeather? = response.body()
                if (response.isSuccessful && dateWeather != null) {
                    val listString= mutableMapOf<String, String>()
                    val nameTown = dateWeather.weather[0].toString()
                    val size = nameTown.length - 1
                    listString.apply {
                        put("nameTown", nameTown.subSequence(13, size).toString())
                        put("temperature", dateWeather.main.temp!!.toInt().toString())
                    }
                    callback.onSuccess(listString)
                } else {
                    callback.onError("请求失败:${response.code()}")
                }
            }
            override fun onFailure(call: Call<DateWeather>, t: Throwable) {
                callback.onError("网络错误:${t.message}")
            }
        })
    }
}

步骤3:Activity中调用并处理结果

class MainActivity : AppCompatActivity() {
    private lateinit var dataProcessing : DataProcessing
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        dataProcessing = DataProcessing()
    }

    private fun showData(townName: String){
        dataProcessing.sendRequest(townName, object : WeatherRequestCallback {
            override fun onSuccess(weatherData: Map<String, String>) {
                // 请求成功,切主线程更新UI
                runOnUiThread {
                    val weather = weatherData["nameTown"]
                    val tem = weatherData["temperature"]
                    Log.d("Egor","two $weather")
                    Log.d("Egor","three $tem")
                    dataShow(weather, tem)
                }
            }

            override fun onError(errorMsg: String) {
                runOnUiThread {
                    Toast.makeText(this@MainActivity, errorMsg, Toast.LENGTH_LONG).show()
                }
            }
        })
    }
}
解决方案2:Kotlin协程(官方推荐更简洁)

如果你的项目已经使用Kotlin协程,可以用更简洁的写法,不需要手动写回调:

步骤1:修改Retrofit接口方法为suspend函数

// 原来的showWeather方法加上suspend关键字,不需要Call包裹
interface WeatherApi {
    @GET("你的接口地址")
    suspend fun showWeather(@Query("townName") townName: String): DateWeather
}

步骤2:修改DataProcessing类

class DataProcessing {
    private val retrofitImpl: RetrofitImpl = RetrofitImpl()

    suspend fun getWeatherData(townName: String): Result<Map<String, String>> {
        return try {
            val dateWeather = retrofitImpl.getRequest().showWeather(townName)
            val listString= mutableMapOf<String, String>()
            val nameTown = dateWeather.weather[0].toString()
            val size = nameTown.length - 1
            listString.apply {
                put("nameTown", nameTown.subSequence(13, size).toString())
                put("temperature", dateWeather.main.temp!!.toInt().toString())
            }
            Result.success(listString)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}

步骤3:Activity中通过生命周期协程域调用

private fun showData(townName: String){
    // lifecycleScope会在Activity销毁时自动取消请求,避免内存泄漏
    lifecycleScope.launch {
        val result = dataProcessing.getWeatherData(townName)
        result.onSuccess { weatherData ->
            val weather = weatherData["nameTown"]
            val tem = weatherData["temperature"]
            Log.d("Egor","two $weather")
            Log.d("Egor","three $tem")
            dataShow(weather, tem)
        }.onFailure { e ->
            Toast.makeText(this@MainActivity, e.message?:"请求失败", Toast.LENGTH_LONG).show()
        }
    }
}
额外注意事项
  • 不要在非Android组件类中实例化Activity、Service等系统组件,所有UI相关操作都要交给持有上下文的组件处理
  • 网络请求要添加取消逻辑,Activity销毁时终止未完成的请求,避免内存泄漏和崩溃

内容的提问来源于stack exchange,提问作者Egor0702

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 23:06:10