【问题标题】:Kotlin Updating value of MutableLiveDataKotlin 更新 MutableLiveData 的值
【发布时间】:2020-04-14 08:59:09
【问题描述】:

我在 MVVM 架构中有一个 Kotlin 项目。 API 是在 Laravel 后端构建的。除非错误响应未更新 UI,否则一切正常。是不是LiveData的问题,我也搞不清楚。

SignUpRepository.kt

val failureResponse = MutableLiveData<JSONObject>()

fun signUp(name: String, email: String, password: String){

        val retrofit = Retrofit.Builder().baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()).build()

        val service = retrofit.create(UserAPIService::class.java)

        service.createUser(name, email, password).enqueue(object : Callback<String>{
            override fun onFailure(call: Call<String>, t: Throwable) {
                Log.d(TAG, "Failure: ${t.localizedMessage}")
            }

            override fun onResponse(call: Call<String>, response: Response<String>) {
                if(response.isSuccessful()){
                    Log.d(TAG, "Success: ${response.body()}")
                } else {
                    var jsonObject: JSONObject? = null
                    try {
                        jsonObject = JSONObject(response.errorBody()!!.string())
                        if(failureResponse.value == null) {
                            failureResponse.value = jsonObject
                        } else {
                            failureResponse.postValue(jsonObject)
                        }
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }
            }
        })
    }

SignUpViewModel.kt

val failureResponse: LiveData<JSONObject>

init {
        this.signUpResponse = repo.signUpResponse
        this.failureResponse = repo.failureResponse
    }

fun signUp(name: String, email: String, password: String){
        repo.signUp(name, email, password)
    }

还有 SignupActivity.kt

btnSignup.setOnClickListener {
            val username = txt_create_username.text.toString()
            val email = txt_create_email.text.toString()
            val password = txt_created_password.text.toString()

            signUpViewModel.stateChange()
            signUpViewModel.signUp(username, email, password)

signUpViewModel.failureResponse.observe(this, Observer {
        nameError.text = (it.getJSONArray("name")).getString(0)
        emailError.text = (it.getJSONArray("email")).getString(0)
        passwordError.text = (it.getJSONArray("password")).getString(0)
     })
}

我想将特定错误打印到相应的文本视图,即 nameError、emailError... 等。但是 nameError、emailError... 没有更新,当我使用 LiveData.PostValue(value) 时,应用程序崩溃了。请帮帮我。

【问题讨论】:

    标签: android kotlin error-handling android-livedata mutablelivedata


    【解决方案1】:

    因为你没有在这里设置任何东西。

    override fun onResponse(call: Call<String>, response: Response<String>) {
                    if(response.isSuccessful()){
                        Log.d(TAG, "Success: ${response.body()}")
                    } else {
                        var jsonObject: JSONObject? = null
                        try {
    
    
                        jsonObject = JSONObject(response.errorBody()!!.string())
                          failureResponse.value = jsonObject 
                        } catch (e: JSONException) {
                            e.printStackTrace()
                        }
                    }
                }
    

    【讨论】:

    • 对不起,我忘记在存储库中添加以下行:jsonObject = JSONObject(response.errorBody()!!.string())。我已经编辑了帖子。
    • 是的,我认为是 View 的问题。我无法第二次向 UI 显示错误消息。 LiveData 正在更新...当我在视图中使用 Log.d("tst", Gson().toJson(it)) 时。请帮我处理视图中的响应。
    • 首先去掉这个条件是没用的。 if(failureResponse.value == null) 再试一次。它应该可以工作
    • 我已经删除了这些行,它返回了 JSONObject。如何将单个 JSON 元素分配给 textview?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 2020-03-09
    相关资源
    最近更新 更多