gpt4 book ai didi

java - android中的登录表单验证

转载 作者:行者123 更新时间:2023-11-29 08:04:22 24 4
gpt4 key购买 nike

我在 Android 中开发了一个登录表单。我在这里使用了验证。我必须填写任何人(用户名或密码)然后我的应用程序应该显示成功!并且应该转移到其他 Activity 。

但是,如果两个字段都为空,则不应显示成功消息,而应显示登录失败!!!

请帮帮我。

这是我的网络服务代码:

public class XcartLogin {
public String authentication(String userName, String password) {
String retrievedUserName = "";
String retrievedPassword = "";
String status = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart432-pro", "root", "");
PreparedStatement statement = con.prepareStatement("SELECT * FROM xcart_customers WHERE login = '" + userName + "'");
ResultSet result = statement.executeQuery();
while (result.next()) {
retrievedUserName = result.getString("login");
retrievedPassword = result.getString("password");
}
if (retrievedUserName.equals(userName) && retrievedPassword.equals(password)) {
status = "Success!";
} else {
status = "Login fail!!!";
}
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
}

这是对我的 android 代码的验证:

if(status.equals("Success!"))
{
// ADD to save and read next time
String strUserName = userName.getText().toString().trim();
String strPassword = userPassword.getText().toString().trim();
if (null == strUserName || strUserName.length() == 0)
{
// showToast("Enter Your Name");
userName.setError( "username is required!" );
isUserValidated = false;
}
if (null == strPassword || strPassword.length() == 0)
{
// showToast("Enter Your Password");
isPasswordValidated = false;
userPassword.setError( "password is required!" );
}
}

最佳答案

在验证代码中的 if(status.equals("Success!")) 语句之前,您应该首先执行此操作,以避免在任何文本字段为空时查询数据库第一名:

boolean errorOccurred = false;
if (strUserName.equals("")) {
userName.setError("Username is required!");
errorOccurred = true;
}

if (strPassword.equals("")) {
userName.setError("Password is required!");
errorOccurred = true;
}

if (errorOccurred) {
return; // avoids executing the part of your code which queries the db
}

检查输入字段的值是否为 null 是毫无意义的,因为如果它们不包含任何内容,它只会是一个空字符串,或者 "" .然后,简化您的网络服务代码...

if (result.next()) { // use if instead of while, because ideally, only ONE record should
// be returned and hence, no need to loop;

// then, just get the corresponding password
retrievedPassword = result.getString("password");
}

if (retrievedPassword.equals(password)) {
status = "Success!";
}

进一步的建议:输入“成功!”在 String 常量中并使用它代替文字值。以这种方式犯错的可能性较小,并且可以更轻松地编辑代码。

关于java - android中的登录表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12345225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com