在lateinit声明后variables不更新,无法返回
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(R.id.recycler_view) recyclerview.layoutManager = LinearLayoutManager(this.activity) //val name3: Array = recyclerview.adapter = CustomAdaptor(fetchJson()) return view1 }
Fetchjson函数
fun fetchJson(): Array { 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 //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::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
类。 我创建了一个后期初始化的variablesname2。 在fetchjson中,json的值不会被更新。
Android Studio提供的错误:
kotlin.UninitializedPropertyAccessException:lateinit属性name2尚未初始化
我应该如何声明variables,以便更新?
您正在使用AsyncTask(意味着您已经调用了一个URL,并且正在等待响应),但是fetchJson()方法不会等待从url接收答案,并将其放在name2中并返回。 在你调用fetchJson()之后,它会启动你的Asynctask并立即返回name2。 而且因为你havnt初始化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::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。 结帐这个链接了解更多。
你声明variables作为一个类级别的静态variables,例如: –
public static int a = 10;
你可以很容易地更新你的variables,也可以从另一个类更新这个variables,但是在包中。
尝试这个:
// DONT DO: lateinit var name2: Array //Initialized name2 // DO: var name2 = arrayListOf () //Initialized name2
- 当我们需要重写Handler的handleMessage()方法
- 编写JS和Java的代码
- Android Studio中过时的Kotlin运行时警告
- Kotlin库’classes.jar’具有不受支持的格式。 请更新库或插件
- 在Android版Firebase中忘记密码
- 使用reflection读取Kotlin函数注释值?
- com.android.builder.dexing.DexArchiveMergerException:无法在运行时合并dexexception
- Kotlin使用Gson的JSONParser解析对象数组
- 智能投到BootsrapButton是不可能的,因为endtrip是这个时候改变了的可变属性