java.lang.NullPointerException: Can‘t toast on a thread that has not called Looper.prepare()-android

val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// 处理请求失败的情况
Toast.makeText(applicationContext,"请求失败",Toast.LENGTH_SHORT).show()
}

当出现错误:java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()

分析:

这个错误是因为在非 UI 线程中尝试显示 Toast 导致的。您可以尝试使用 runOnUiThread 方法在 UI 线程中显示 Toast。例如:

runOnUiThread {
    Toast.makeText(applicationContext, "请求失败", Toast.LENGTH_SHORT).show()
}

猜你喜欢

转载自blog.csdn.net/streetrust/article/details/131131427