在lateinit声明后变量未更新,无法返回

时间:2018-01-16 11:48:14

标签: android kotlin

OnCreateView功能

 override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)

        val view1 = inflater?.inflate(R.layout.fragment_home, container, false)
        val recyclerview = view1!!.findViewById<RecyclerView>(R.id.recycler_view)

        recyclerview.layoutManager = LinearLayoutManager(this.activity)


        //val name3: Array<Articles> =


        recyclerview.adapter = CustomAdaptor(fetchJson())

        return view1

    }

Fetchjson功能

    fun fetchJson(): Array<Articles> {
    println("Attempting to fetch JSON")
    val url1 = "https://go-api-api.herokuapp.com/"

    //var a1 = Articles(1, "rsdfd", "fdsadfd", 2345, 3)

    lateinit var name2: Array<Articles>  //Initialized name2

    val request = Request.Builder().url(url1).build()
    val client = OkHttpClient()
    client.newCall(request).enqueue(object : Callback {
        override fun onResponse(call: Call?, response: Response?) {
            val body = response?.body()?.string()
            println(body)

            val gson = GsonBuilder().create()

            try {
                name2 = gson.fromJson(body, Array<Articles>::class.java)  //Updating value of name2
            }
            catch (e: Exception){
                print("Error roroorirorr")
                print(e)
            }
        }

        override fun onFailure(call: Call?, e: IOException?) {
            println("Faild to execute request")
        }
    })
    return name2   //returning name2
}

CustomAdaptor接受输入Article课程。我创建了一个后期初始化变量name2。在fetchjson中,json的值不会更新。

Android Studio提供错误:

  

kotlin.UninitializedPropertyAccessException:lateinit属性name2尚未初始化

我应该如何声明变量,以便更新它?

3 个答案:

答案 0 :(得分:2)

您正在使用AsyncTask(意味着您已经调用了URL并且您正在等待响应),但fetchJson()方法不等待从url接收答案并将其放入name2并返回它。在调用fetchJson()之后,它会启动你的Asynctask并立即返回name2。并且因为你曾经初始化name2,你会收到一个错误。所以你应该将你的代码更改为:

  client.newCall(request).enqueue(object : Callback {
    override fun onResponse(call: Call?, response: Response?) {
        val body = response?.body()?.string()
        println(body)

        val gson = GsonBuilder().create()

        try {
            name2 = gson.fromJson(body, Array<Articles>::class.java) 
            someMethodCallToReturnTheValue(name2)
         //Updating value of name2
        }
        catch (e: Exception){
            print("Error roroorirorr")
            print(e)
        }
    }

    override fun onFailure(call: Call?, e: IOException?) {
        println("Faild to execute request")
         someMethodCallToInformError()
    }
})

更新:正如Marko Topolnik在评论中提到的那样,你也可以在kotlin中使用Coroutines。 结帐this链接了解详情。

答案 1 :(得分:-1)

您将变量声明为类级静态变量,例如: -

           public static int a = 10;

您可以轻松更新您的变量,也可以在另一个类中更新此变量但是在包中..

答案 2 :(得分:-1)

试试这个:

// DONT DO: lateinit var name2: Array<Articles>  //Initialized name2
// DO: var name2 = arrayListOf<Articles>()  //Initialized name2