Обернут в ссылочный объект, который будет изменен при захвате в замыкании - PullRequest
0 голосов
/ 21 февраля 2020

, поэтому я немного новичок в Kotlin по android и очень запутался в том, что такое " CLOSURES ". Я также посмотрел тонну видео, но ничего.

Я заканчиваю sh, инициализирую взаимный список в строке 5, но тогда я не могу установить для него значения в try / catch блок.

Может кто-нибудь, пожалуйста, помогите мне.

private fun returnArray(url: String) : MutableList<String> {

    Log.d("Alele", "returnArray(url)")

    var arrayList = mutableListOf<String>()

    val jsonObjectRequest = JsonObjectRequest(
            Request.Method.GET,
            url,
            null,
            Response.Listener { response ->
                try {

                    Log.d("Alele", "Try block")
                    var jsonObject = response.getJSONObject("response").getJSONArray("docs").getJSONObject(0)

                    Log.d("Alele", jsonObject.toString())

                    var id = jsonObject.getString("id")
                    Log.d("Alele", id.toString())

                    var journal = jsonObject.getString("journal")
                    Log.d("Alele", journal)

                    arrayList[0] = id
                    arrayList[1] = journal

                } catch (e: JSONException) {
                    Log.d("Alele", "catch block")
                    e.printStackTrace()
                }
            },
            Response.ErrorListener {
                it.printStackTrace()
                Log.d("Alele", it.printStackTrace().toString())
            })
    Log.d("Alele", " $arrayList[0]")
    Log.d("Alele", " $arrayList[1]")

    // add the queue to the request
    requestQueue.add(jsonObjectRequest)
    return arrayList
}


Это журнал производит. Все распечатывается, как и ожидалось, однако, строки

                    arrayList[0] = id
                    arrayList[1] = journal

заставляют приложение обрабатывать sh, и всякий раз, когда я помещаю курсор в эти строки для любых подсказок, я получаю , обернутый в ссылочный объект быть измененным, когда захвачено в закрытии , что довольно запутанно для меня, чтобы понять.

2020-02-21 10:22:48.560 31603-31603/com.hylton.volleyproject D/Alele: returnArray(url)

2020-02-21 10:22:48.563 31603-31603/com.hylton.volleyproject D/Alele:  [][0]

2020-02-21 10:22:48.563 31603-31603/com.hylton.volleyproject D/Alele:  [][1]

2020-02-21 10:22:51.108 31603-31603/com.hylton.volleyproject D/Alele: Try block

2020-02-21 10:22:51.110 31603-31603/com.hylton.volleyproject D/Alele: {"id":"10.1371\/journal.pone.0084896","journal":"PLoS ONE","eissn":"1932-6203","publication_date":"2014-01-17T00:00:00Z","article_type":"Research Article","author_display":["Marcel A. L. M. van Assen","Robbie C. M. van Aert","Michèle B. Nuijten","Jelte M. Wicherts"],"abstract":["Background: De Winter and Happee [1] examined whether science based on selective publishing of significant results may be effective in accurate estimation of population effects, and whether this is even more effective than a science in which all results are published (i.e., a science without publication bias). Based on their simulation study they concluded that “selective publishing yields a more accurate meta-analytic estimation of the true effect than publishing everything, (and that) publishing nonreplicable results while placing null results in the file drawer can be beneficial for the scientific collective” (p.4). Methods and Findings: Using their scenario with a small to medium population effect size, we show that publishing everything is more effective for the scientific collective than selective publishing of significant results. Additionally, we examined a scenario with a null effect, which provides a more dramatic illustration of the superiority of publishing everything over selective publishing. Conclusion: Publishing everything is more effective than only reporting significant outcomes. "],"title_display":"Why Publishing Everything Is More Effective than Selective Publishing of Statistically Significant Results","score":9.342657}

2020-02-21 10:22:51.110 31603-31603/com.hylton.volleyproject D/Alele: 10.1371/journal.pone.0084896

2020-02-21 10:22:51.110 31603-31603/com.hylton.volleyproject D/Alele: PLoS ONE

Это то, что печатает отчет cra sh

E/AndroidRuntime: FATAL EXCEPTION: main

    Process: com.hylton.volleyproject, PID: 569

    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

        at java.util.ArrayList.set(ArrayList.java:453)

        at com.hylton.volleyproject.MainActivity$returnArray$jsonObjectRequest$1.onResponse(MainActivity.kt:71)

        at com.hylton.volleyproject.MainActivity$returnArray$jsonObjectRequest$1.onResponse(MainActivity.kt:26)

        at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:90)

        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)

        at android.os.Handler.handleCallback(Handler.java:883)

        at android.os.Handler.dispatchMessage(Handler.java:100)

        at android.os.Looper.loop(Looper.java:214)

        at android.app.ActivityThread.main(ActivityThread.java:7356)

        at java.lang.reflect.Method.invoke(Native Method)

        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)

        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

I/Process: Sending signal. PID: 569 SIG: 9

Application terminated.
...