You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin新手:AsyncTask的onPostExecute中if表达式类型不匹配问题

Hey there! Let's fix this issue step by step. The error "Type mismatch. Required: Boolean Found: String?" happens because your handleJson function currently returns no value (it defaults to Unit, which is Kotlin's equivalent of Java's void), but you’re trying to use it as a condition in an if statement— which expects a Boolean result.

Here's how to adjust your code to meet your requirement:

1. Modify handleJson to return a Boolean

We’ll update the function to return true if it executes successfully, and false if any error occurs (like invalid JSON, null input, or parsing failures). We’ll wrap the logic in a try-catch block to catch exceptions:

@SuppressLint("WrongViewCast")
private fun handleJson(jsonString: String?): Boolean {
    return try {
        // Early exit if the input is null
        jsonString ?: return false
        
        val jsonObj = JSONObject(jsonString)
        val result = jsonObj.getJSONObject("result")
        val response = result.getJSONObject("response")
        // Fixed the undefined "arrivals" variable to use "response" (adjust if needed)
        val jsonArray = JSONArray(response.get("data").toString())
        
        val list = ArrayList<FlightShdu>()
        var x = 0
        while (x < jsonArray.length()) {
            val jsonObject = jsonArray.getJSONObject(x)
            list.add(
                FlightShdu(
                    jsonObject.getJSONObject("flight").getJSONObject("identification").getJSONObject("number").getString("default"),
                    jsonObject.getJSONObject("flight").getJSONObject("airline").getString("short"),
                    jsonObject.getJSONObject("flight").getJSONObject("status").getJSONObject("generic").getJSONObject("status").getString("text"),
                    jsonObject.getJSONObject("flight").getJSONObject("airline").getJSONObject("code").getString("icao"),
                    jsonObject.getJSONObject("flight").getJSONObject("time").getJSONObject("scheduled").getString("arrival"),
                    jsonObject.getJSONObject("flight").getJSONObject("airport").getJSONObject("origin").getJSONObject("position").getJSONObject("region").getString("city"),
                    jsonObject.getJSONObject("flight").getJSONObject("aircraft").getJSONObject("model").getString("code"),
                    jsonObject.getJSONObject("flight").getJSONObject("time").getJSONObject("real").getString("departure"),
                    jsonObject.getJSONObject("flight").getJSONObject("time").getJSONObject("estimated").getString("arrival"),
                    jsonObject.getJSONObject("flight").getJSONObject("aircraft").getString("registration"),
                    jsonObject.getJSONObject("flight").getJSONObject("status").getJSONObject("generic").getJSONObject("status").getString("diverted"),
                    jsonObj.getString("timestamp"),
                    jsonObject.getJSONObject("flight").getJSONObject("status").getString("icon")
                )
            )
            x++
        }
        
        list.forEach(::println)
        val adapter = ListAdapteArr(this@MainActivity, list)
        flight_arrivel_list.adapter = adapter
        
        true // Return true if all logic executes without errors
    } catch (e: Exception) {
        e.printStackTrace() // Print error for debugging
        false // Return false if any exception occurs
    }
}

Note: I fixed the undefined arrivals variable to use response— adjust this back if you had a different intended variable.

2. Update onPostExecute to use the Boolean result

Now that handleJson returns a Boolean, we can use it in your if expression to show the error dialog when needed:

override fun onPostExecute(result: String?) {
    dialog.dismiss() // Always dismiss the progress dialog first
    
    if (handleJson(result)) {
        // Optional: Add any extra logic for successful execution here
    } else {
        // Show connectivity error dialog
        AlertDialog.Builder(this@MainActivity)
            .setTitle("Connection Error")
            .setMessage("Sorry you don't have proper internet connectivity")
            .setPositiveButton("OK") { dialog, _ -> dialog.dismiss() }
            .setCancelable(true)
            .show()
    }
}

Bonus: Improve doInBackground for better error handling

Right now, if your network request fails, doInBackground will throw an exception and skip onPostExecute entirely. Let’s adjust it to return null on network errors, so our handleJson function can catch it:

override fun doInBackground(vararg url: String?): String? {
    val targetUrl = url[0] ?: return null
    return try {
        val connection = URL(targetUrl).openConnection() as HttpURLConnection
        connection.connectTimeout = 5000
        connection.readTimeout = 5000 // Add read timeout to avoid hanging
        connection.connect()
        
        // Check if the response is successful
        if (connection.responseCode != HttpURLConnection.HTTP_OK) {
            return null
        }
        
        connection.inputStream.use { it.reader().use { reader -> reader.readText() } }
    } catch (e: IOException) {
        e.printStackTrace()
        null // Return null on network failures
    }
}

Quick Side Note

Keep in mind that AsyncTask is deprecated in Android API 30+. If you’re new to Kotlin and Android, learning Coroutines is a better long-term solution for asynchronous tasks— it’s more modern and easier to maintain!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:53:58