我正在创建登录page.What,我已经完成了-->
1.当用户键入正确的登录详细信息时-->将把他带到下一个成功的主页
2.当用户键入错误的登录详细信息时-->从API显示错误响应,表明电子邮件或密码错误,请稍后再试。
所以基本上我想要的是-->当用户忘记填写像电子邮件或密码这样的字段时,它应该从API给出类似“数据丢失”的响应。
下面是我的json:
{
"status": 400,
"message": "Data missing.",
"user_msg": "Data missing"
}这是我到目前为止所做的代码-->
loginbtn.setOnClickListener {
val email = loginuser.text.toString().trim()
val password = loginpassword.text.toString().trim()
if (email.isEmpty()) {
loginuser.error = "Email required"
loginuser.requestFocus()
return@setOnClickListener
}
if (password.isEmpty()) {
loginpassword.error = "Password required"
loginpassword.requestFocus()
return@setOnClickListener
}
override fun onResponse(
call: Call<LoginResponse>,
response: Response<LoginResponse>
) {
var res = response
Log.d("response check ", "" + response.body()?.status.toString())
if (res.body()?.status==200) {
// when typed right details
SharedPrefManager.getInstance(applicationContext)
.saveUser(response.body()?.data!!)
val intent = Intent(applicationContext, HomeActivity::class.java)
intent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
Toast.makeText(
applicationContext,
res.body()?.message,
Toast.LENGTH_LONG
).show()
Log.d("kjsfgxhufb",response.body()?.status.toString())
startActivity(intent)
finish()
}
else
{
//when typed wrong details
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
Toast.makeText(
applicationContext,
jObjError.getString("message")+jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr",e.message)
}
}
}
})
}所以我想知道当用户忘记填写任何字段,如电子邮件或密码时,上述json的逻辑。因此它必须显示为toast中缺少数据。
需要帮助...Thanks
发布于 2020-06-22 14:21:34
首先检查字段是否为空,然后不能进行API调用,如果字段数据只是相关的,则应该进行API调用。例如,用于
// make a validation check if the field(in this case edittext) is empty or not
private boolean validate(EditText editText) {
// check the lenght of the enter data in EditText and give error if its empty
if (editText.getText().toString().trim().length() > 0) {
return true; // returs true if field is not empty
}
editText.setError("Please Fill This");
editText.requestFocus();
return false;
}
// then wherever you want to do the api call first validate the fields that it is empty or not
// validate the fields and call sign method to implement the api
if (validate(field1) && validate(field2) && validate(field3)) {
yourApiMethodCall();
}发布于 2020-06-22 14:22:18
您可以在请求完成之前验证它,而不是在请求完成后进行检查
例如,
void checkValidation()
{
if(username.getText().equals("")){
//show appropriate message like
username.setError("Please enter username");
return false;
}
if(password.getText().equals("")){
//show appropriate message like
username.setError("Please enter username");
return false;
}
return true;}
和
if(checkValidation){
//Make request here
}如果你真的想要响应,你必须在服务器端进行编码。
发布于 2020-06-22 14:45:23
当您从服务器获得响应时,做一件事:
https://stackoverflow.com/questions/62508345
复制相似问题