Android登录功能仅支持列表最后一位用户登录问题排查
Hey there, let's figure out why only the last user can log in. The issue comes down to two key mistakes in your code:
You're overwriting a local
usersvariable instead of using the global one
In youronResponsemethod, you create a new localList<User> userswhich shadows the globaluserslist you declared at the top of your class. That means the global list never actually gets populated with the user data from your API.You're overwriting
usernameApiandpasswordApiwith every user in the loop
Your for loop iterates through all users, but each time it replacesusernameApiandpasswordApiwith the current user's credentials. By the end of the loop, these variables only hold the last user's info—so only that user can pass the login check.
Fix Steps & Updated Code
First, fix the global users list assignment:
In onResponse, remove the local List<User> users declaration and assign directly to the global variable:
// Replace this line: // List<User> users = new Gson().fromJson(userData, listType); // With this: users = new Gson().fromJson(userData, listType);
Next, remove the unnecessary for loop that overwrites usernameApi and passwordApi—you don't need those single variables anymore. Instead, check against the entire users list in your login method.
Update your login method to iterate through all users and find a match:
public void login(String usernameInput, String passwordInput) { boolean isUserValid = false; // Iterate through all users to check for a match for(User user : users) { if (user.getUsername().equals(usernameInput) && user.getPassword().equals(passwordInput)) { isUserValid = true; break; // Exit loop early once we find a match } } if (isUserValid) { Intent i = new Intent(this, PostsActivity.class); startActivity(i); finish(); } else { // Add a toast to inform the user of invalid credentials (better than silent disable) Toast.makeText(this, "Invalid username or password", Toast.LENGTH_SHORT).show(); // login_btn.setEnabled(false); // Optional: keep if needed, but consider re-enabling after a delay } }
Bonus Notes
- Double-check that your
Userclass has properly implementedgetUsername()andgetPassword()methods that match the JSON keys from your API (which they appear to, since you could retrieve the last user's data). - Adding a toast message gives clear feedback to users instead of just disabling the button without explanation.
内容的提问来源于stack exchange,提问作者Marko Lazarevic

