【问题标题】:Is there a way to access response outside of the JsonObjectRequest?有没有办法在 JsonObjectRequest 之外访问响应?
【发布时间】:2021-09-10 18:55:19
【问题描述】:

使用 Volley,我正在创建一个名为 jsonRequest 的 JsonObjectRequest。我想访问jsonRequest 之外的响应,以便将其发送到其他活动。如果我执行val jsonResult = response 并尝试在intent.putExtra("response", jsonResult) 中访问它,我会收到“未解决的引用”错误。我该怎么做?我的代码如下:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val itemsURL = "https://prices.csgotrader.app/latest/prices_v6.json"
        val requestQ = Volley.newRequestQueue(this@MainActivity)

        val jsonRequest = JsonObjectRequest(
            Request.Method.GET, itemsURL, null,
            { response ->
                TODO() // JsonResult
            },
            { error ->
                val dialogBuilder = AlertDialog.Builder(this)
                dialogBuilder.setTitle("Error")
                dialogBuilder.setMessage(error.message)
                dialogBuilder.create().show()
            })
        requestQ.add(jsonRequest)

        main_activity_btnSearch.setOnClickListener {
            val intent = Intent(this, SearchActivity::class.java)
            intent.putExtra("response", jsonResult)
            startActivity(intent)
        }

        main_activity_btnPortfolio.setOnClickListener {
            TODO()
        }

        main_activity_btnTrending.setOnClickListener {
            TODO()
        }
    }
}

【问题讨论】:

    标签: android android-volley


    【解决方案1】:

    你有三种方式:

    1. 使用var json = JsonObject() 之类的字段创建类,并在获得时设置它。

    2. 将它像字符串一样发送到另一个活动并将其转换为JsonObject:

      val answer = JSONObject(string_from_intent)
      
    3. 如果您最终将此 jsonobject 转换为模型类,您可以通过 Intent Parcelable 模型类发送到另一个活动。

    【讨论】:

      【解决方案2】:

      谷歌最佳实践:

      实现您的案例的最佳方法是使用LiveData

      当您的 api 调用完成后,您需要使用更新您的 liveData

      liveData.postValue("your response data")
      

      您可以从您的活动中观察 liveData,使用此方法您可以在运行时将您的 api 响应获取到活动中。

      YourApiClass.livedata.observe(viewLifecycleOwner) {
             // Here you can update your UI with the live data coming from api
         }
      

      详情请查看Android App Architecture

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-19
        • 2013-11-04
        • 1970-01-01
        • 1970-01-01
        • 2022-08-02
        • 2019-06-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多