在OnViewCreated变量中分配函数值

时间:2018-12-20 18:22:00

标签: android android-studio kotlin

我正在尝试从函数中获取JSON值,并尝试在onViewCreated方法内分配该值。代码工作正常,但是我不确定如何在onViewCreated变量中分配值。任何帮助表示赞赏。

主要活动

var volleyRequest: RequestQueue?=null
val testlLink="https://www.abc.app"     
override fun onViewCreated(view: View, savedInstanceState: Bundle?)
{
super.onViewCreated(view, savedInstanceState)
volleyRequest=Volley.newRequestQueue(this.context)
getTestData(testlLink)
val data=??????????????????
}

功能

fun getTestData(Url:String)
{

    val testRequest = StringRequest(Request.Method.GET, Url, Response.Listener {
        response: String ->
        try {
    Log.d("Response:",response)
        }catch (e: JSONException) { e.printStackTrace()}

    },
            Response.ErrorListener {
                error: VolleyError? ->
                try {
                    Log.d("Error:", error.toString())

                }catch (e: JSONException){e.printStackTrace()}
            })
    volleyRequest!!.add(testRequest)
}

1 个答案:

答案 0 :(得分:1)

您不能将请求的结果分配给变量,因为它是异步执行的。相反,您有几种选择,例如coroutinesRxJava,但是一个简单的解决方案可能是只传递将在响应到达后执行的回调函数。

示例

lateinit var requestQueue: RequestQueue

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

    requestQueue = Volley.newRequestQueue(this)

    getTestData("https://jsonplaceholder.typicode.com/todos/1",
        { body -> Log.d("Network", "Success: $body") },
        { error -> Log.d("Network", "Error", error) }
    )
}

override fun onDestroy() {
    super.onDestroy()
    requestQueue.cancelAll { true }
}

private fun getTestData(url: String, onSuccess: (String) -> Unit, onError: (Throwable) -> Unit) {
    val testRequest =  StringRequest(Request.Method.GET, url,
        Response.Listener { onSuccess(it) },
        Response.ErrorListener { onError(it)}
    )
    requestQueue.add(testRequest)
}

输出

D/Network: Success: {
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}