多次单击“登录”按钮后,Livedata对象中的改装响应未更新
我已经创建了一个存储库来更新实时数据,但是它不起作用
首先,我输入了错误的凭据,然后输入了正确的凭据。 尽管如此,我得到的回应还是一样
LoginViewModel.kt
fun getNumber(phone: String, password: String): MutableLiveData<String> {
Log.i(TAG, "Get number")
if (responseData == null) {
responseData = MutableLiveData<String>()
this.phone = phone
this.password = password
createNumber()
}
return responseData as MutableLiveData<String>
}
fun createNumber() {
var apiServices = APIClient.client.create(APIInterface::class.java)
val call = apiServices.getdata(phone, password)
call.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
responseData?.value = t.message
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
responseData?.value = response.body()?.string()
}
})
}
LoginActivity.kt
btn_login!!.setOnClickListener {
if (edit_userName!!.editableText.toString() != ""
&& edit_passWord!!.editableText.toString() != "") {
layout_progress!!.visibility = View.VISIBLE;
model?.getNumber(edit_userName!!.editableText.trim().toString(), edit_passWord!!.editableText.trim().toString())
?.observe(this, Observer {
var jsonobject: JSONObject = JSONObject(it)
var message: String = jsonobject.getString("message")
if (message.equals("Login Success")) {
startActivity(Intent(this, HomeActivity::class.java))
finish()
} else {
Toast.makeText(
this,
"You are not registered User....Please Contact Admin",
Toast.LENGTH_LONG
).show()
layout_progress?.visibility = View.GONE
}
})
} else {
Toast.makeText(applicationContext, "Username and Password should not be empty", Toast.LENGTH_LONG).show()
}
}
答案 0 :(得分:0)
您可以这样更改代码
fun getNumber(): MutableLiveData<String> {
if (responseData == null) {
responseData = MutableLiveData<String>()
}
return responseData as MutableLiveData<String>
}
fun createNumber(phone: String, password: String) {
var apiServices = APIClient.client.create(APIInterface::class.java)
val call = apiServices.getdata(phone, password)
call.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
responseData?.value = t.message
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
responseData?.value = response.body()?.string()
}
})
}
model?.getNumber()
?.observe(this, Observer {
var jsonobject: JSONObject = JSONObject(it)
var message: String = jsonobject.getString("message")
if (message.equals("Login Success")) {
startActivity(Intent(this, HomeActivity::class.java))
finish()
} else {
Toast.makeText(
this,
"You are not registered User....Please Contact Admin",
Toast.LENGTH_LONG
).show()
layout_progress?.visibility = View.GONE
}
})
btn_login!!.setOnClickListener {
model?.currentNumber(edit_userName!!.editableText.trim().toString(), edit_passWord!!.editableText.trim().toString())
}