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

Android onPostExecute中创建JSONObject时Activity崩溃

崩溃原因

你遇到的崩溃本质是未处理的JSON解析异常,触发逻辑如下:

  • onPostExecute 接收的参数 result 是可空类型 String?,你没有做任何前置校验就直接传入 JSONObject 构造函数
  • 网络请求逻辑里,只要请求出错(超时、非200状态码、其他网络异常),返回的result都是普通文本(比如Connection timed out、Error xxx、HTTP响应消息),完全不符合JSON格式
  • JSONObject 构造函数接收到非JSON格式的字符串、或者null值时,会直接抛出JSONException,你没有捕获这个异常,就会导致应用直接崩溃

另外你注释掉的代码块里存在大量语法错误,后续如果放开注释还会遇到编译失败问题,包括但不限于:使用中文引号、变量名大小写不匹配、Val关键字大小写错误、字符串模板$符号位置写反、optJSONArray()调用未传参数。

修复步骤
  • 首先清理无用导入:删除没有用到的androidx.loader.content.AsyncTaskLoader、java.sql.Connection导入,避免冗余
  • 在onPostExecute中先对返回结果做非空判断,所有JSON解析逻辑全部包裹在try-catch块中,不要默认接口返回一定是合法JSON
  • 修正注释块里的语法错误,所有从JSON中取出的对象、数组提前做非空判断,避免空指针
修正后的核心代码

onPostExecute 方法正确实现如下:

override fun onPostExecute(result: String?) {
    super.onPostExecute(result)
    cancelProgressDialog()
    Log.i("JSON RESPONSE RESULT", "$result")

    if (result.isNullOrBlank()) {
        Log.e("API_ERROR", "接口返回为空")
        return
    }

    try {
        val jsonObject = JSONObject(result)
        val message = jsonObject.optString("message")
        Log.i("message", message)
        val user_id = jsonObject.optInt("USER_ID")
        Log.i("user_id", "$user_id")
        val profiledetails = jsonObject.optJSONObject("profile_details")
        val is_profile_completed = profiledetails?.optString("IS_PROFILE_COMPLETED")
        Log.i("is_profile_completed", "$is_profile_completed")
        val dataListArray = jsonObject.optJSONArray("data-list")
        if (dataListArray != null) {
            Log.i("Data list size", "${dataListArray.length()}")
            for(item in 0 until dataListArray.length()){
                Log.i("value $item", "${dataListArray[item]}")
                val dataItemObject = dataListArray[item] as JSONObject
                val id = dataItemObject.optInt("id")
                Log.i("ID", "$id")
                val value = dataItemObject.optString("value")
                Log.i("value", "$value")
            }
        }
    } catch (e: Exception) {
        Log.e("JSON_PARSE_ERROR", "解析失败,返回内容不是合法JSON: ${e.message}")
    }
}
额外建议

AsyncTask 已经在Android 11版本被官方废弃,后续做网络请求建议使用Retrofit/OkHttp配合Kotlin协程实现,代码可维护性和稳定性都会更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 05:06:26