我的程序中有一个监听器,我猜它被错误地使用了

3pmvbmvn  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(235)

我的程序中有一个响应监听器,我得到了关于它的反馈,就像它被很好地使用一样。

val jsonObjectRequest = object : JsonObjectRequest(
                        Method.POST,
                        url,
                        sendOrder,
                        Response.Listener {

                            val response = it.getJSONObject("data")
                            val success = response.getBoolean("success")
                            val LAUNCH_SECOND_ACTIVITY = 1
                            if (success) {
                                val intent = Intent(this, PaymentActivity::class.java)
                                intent.putExtra("total_amount",totalAmount)

                                startActivityForResult(intent,LAUNCH_SECOND_ACTIVITY)

                            } else {
@@ -116,7 +118,7 @@ class CartActivity : AppCompatActivity() {
                            cartProgressLayout.visibility = View.INVISIBLE
                        },

这是我得到的反馈,这意味着什么,如何改变?
始终处理意外响应,如不同的键或值、json结构或空响应

tyky79it

tyky79it1#

您需要引入异常处理,以便 JSON 不满足给定结构您的应用程序不会崩溃

try{
    val response = it.getJSONObject("data")          // This line can throw exception, if not handled it can cause your app to crash
    val success = response.getBoolean("success")     // This can also throw exception
    val LAUNCH_SECOND_ACTIVITY = 1
    if (success) {
        val intent = Intent(this, PaymentActivity::class.java)
        intent.putExtra("total_amount",totalAmount)
        startActivityForResult(intent,LAUNCH_SECOND_ACTIVITY)
    }
}
catch(jsonException: JSONException){
    // Json parsing failed, notify user if required
}
catch(e: Exception){
    // Something else failed, notify user if required
}

相关问题