【问题标题】:I have a listener in my progam which I guess is wrongfully used我的节目中有一个听众,我猜这个听众被错误地使用了
【发布时间】:2021-07-26 06:41:20
【问题描述】:

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

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 结构或空响应

【问题讨论】:

  • 也就是说,有可能得到一个没有“数据”或“成功”的响应,getJSONObject 会抛出异常。在这种情况下,您希望您的应用程序做什么?崩溃?
  • 不行,那我应该怎么处理呢?
  • 您可以使用改造来代替:P

标签: android xml android-studio kotlin


【解决方案1】:

您需要引入异常处理,这样如果收到的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
}

【讨论】:

  • catch (e: JSONException) { Toast.makeText( this, "Some unexpected error occurred!!", Toast.LENGTH_SHORT ).show() } 我已经有了这个 catch。
  • 我在您发布的代码中没有看到它
  • 是否有异常,如果我没有得到响应,diff Json 结构,不同的键???
猜你喜欢
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 2022-12-13
  • 1970-01-01
  • 1970-01-01
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多