Accessing local variable in lambda in Kotlin

痴心易碎 提交于 2020-02-07 01:59:00

问题


I want to save data acquired from Volley, But lambda used in VolleyRequest function(which gets json data from server) blocks it.

How should I change local variable that is in outside of lambda? Thanks in advance.

class ConDataforReturn( val title:String , val imgDataList: ArrayList<ConImgData>)

fun getConData(context: Context, idx : String):ConDataforReturn{
        val params = HashMap<String,String>()
        var cd = arrayListOf<ConImgData>()
        var title =""
        params.put("package_idx",idx)
        Log.e("idx size",idx.length.toString())
        VolleyRequest(context,params,"https://dccon.dcinside.com/index/package_detail") { response ->
            val answer = JSONObject(response)
            var json = answer.getJSONArray("detail")

            title = answer.getJSONObject("info").getString("title")
            Log.d("title",title)//Prints right data
            for (i in 0..(json.length() - 1)) {
                val v = json.getJSONObject(i)
                cd.add(ConImgData(v.getString("title"), v.getString("ext"), v.getString("path")))
            }

        }
        return ConDataforReturn(title,cd)//returns ConDataforReturn("",arrayListOf<ConImgData>())
    }

回答1:


Here the the code from were you are calling this method

getConData(this, "id") { condata ->

}

Now, your method look like this,

fun getConData(context: Context, idx : String, returnConData : (condata : ConDataforReturn) -> Unit){
        val params = HashMap<String,String>()
        var cd = arrayListOf<ConImgData>()
        var title =""
        params.put("package_idx",idx)
        Log.e("idx size",idx.length.toString())
        VolleyRequest(context,params,"https://dccon.dcinside.com/index/package_detail") { response ->
            val answer = JSONObject(response)
            var json = answer.getJSONArray("detail")

            title = answer.getJSONObject("info").getString("title")
            Log.d("title",title)//Prints right data
            for (i in 0..(json.length() - 1)) {
                val v = json.getJSONObject(i)
                cd.add(ConImgData(v.getString("title"), v.getString("ext"), v.getString("path")))
            }
            returnConData(ConDataforReturn(title,cd)) //returns ConDataforReturn("",arrayListOf<ConImgData>())
        }
    }


来源:https://stackoverflow.com/questions/59942381/accessing-local-variable-in-lambda-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!