我使用云Firestore作为数据库,当我点击登录按钮时,它首先没有更新值,但是第二次点击它会更新。
当我点击Login时,首先它会获取空值,但是在第二次点击时它会获取输入的值。当我更改文本并再次按下登录时,会发生相同的情况,它会使用以前的值,而在第二次单击时会采用更新的值。
public class LoginActivity extends AppCompatActivity {
private TextView appName;
private TextInputEditText registrationNumber;
private TextInputEditText password;
private User userSent;
private FirebaseFirestore db;
private CollectionReference collectionReference;
String result="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = FirebaseFirestore.getInstance();
db.enableNetwork();
collectionReference = db.collection("/user");
registrationNumber = findViewById(R.id.regno);
password = findViewById(R.id.password);
userSent = new User();
appName = findViewById(R.id.appname);
AssetManager assetManager = getApplicationContext().getAssets();
Typeface typeface = Typeface.createFromAsset(assetManager,"fonts/Ubuntu-Regular.ttf");
appName.setTypeface(typeface);
}
public void onLogin(View view){
userSent.setRegistrationNumber(registrationNumber.getText().toString());
userSent.setPassword(password.getText().toString());
if(!userSent.getRegistrationNumber().isEmpty() && !userSent.getPassword().isEmpty()) {
authenticateUser(userSent);
}
else{
Toast.makeText(this, "Registration Number or Password cannot be empty", Toast.LENGTH_LONG).show();
}
//Login Result
Log.d("Login Result: " , result);
if(result.contains("success")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
else if(result.length()>0){
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
}
public void authenticateUser(final User sUser){
final String registration_number = sUser.getRegistrationNumber();
final String password = sUser.getPassword();
collectionReference.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(QueryDocumentSnapshot queryDocumentSnapshot: queryDocumentSnapshots){
Map<String, Object> map;
map = queryDocumentSnapshot.getData();
String reg_no = (String) map.get("registration_number");
String pass = (String)map.get("password");
if(registration_number.equals(reg_no) && password.equals(pass)){
result = "success";
return;
}
else if(registration_number.equals(reg_no)){
result = "Incorrect Password";
return;
}
else{
result = "User does not exist";
}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
result = "Error Connecting to Server";
}
});
}
}