You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. You're overwriting a local users variable instead of using the global one
    In your onResponse method, you create a new local List<User> users which shadows the global users list you declared at the top of your class. That means the global list never actually gets populated with the user data from your API.

  2. You're overwriting usernameApi and passwordApi with every user in the loop
    Your for loop iterates through all users, but each time it replaces usernameApi and passwordApi with 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 User class has properly implemented getUsername() and getPassword() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:43:02