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

Android Studio登录:成功跳转页面与失败提示实现求助

Hey there! Let's tackle your two login-related issues one by one, with specific code tweaks based on your existing LoginActivity.java:

1. 实现登录失败时弹出「用户名/密码错误」的Toast

Right now, your code only shows a toast in the onFailure method (which handles network errors like no internet or server connection issues). But we also need to handle cases where the server returns a successful HTTP status code, but the login fails due to invalid credentials. Here's how to adjust the code:

Step 1: Update the onResponse method

Add checks for business-level login failure (adjust based on your API's actual response format) and show the toast accordingly:

@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
    progress.dismiss(); // Move this to the top to ensure the progress dialog always closes
    if (response.isSuccessful() && response.body() != null) {
        try {
            String data = response.body().string();
            JSONObject jsonObject = new JSONObject(data);
            
            // Check if login failed at the business level (e.g., API returns error info or empty user ID)
            if (jsonObject.has("error") || jsonObject.getString("id").isEmpty()) {
                Toast.makeText(LoginActivity.this, "用户名/密码错误", Toast.LENGTH_LONG).show();
                return;
            }

            // Keep your existing code to save user info to Constants
            Constants.uid = Integer.parseInt(jsonObject.getString("id"));
            Constants.username = jsonObject.getString("username");
            Constants.email = jsonObject.getString("email");
            Constants.credit = jsonObject.getString("credit");
            Constants.qr_code = jsonObject.getString("qr_code");
            Constants.created_at = jsonObject.getString("created_at");
            Constants.updated_at = jsonObject.getString("updated_at");

            // We'll add the jump logic here in the next section

        } catch (IOException | JSONException e) {
            e.printStackTrace();
            Toast.makeText(LoginActivity.this, "登录失败,请重试", Toast.LENGTH_LONG).show();
        }
    } else {
        // Handle HTTP errors like 401 Unauthorized
        Toast.makeText(LoginActivity.this, "用户名/密码错误", Toast.LENGTH_LONG).show();
    }
}

Step 2: Clean up the onFailure method

Update the toast message to match your requirement:

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
    progress.dismiss();
    // You can also use "网络异常,请检查网络后重试" if you want to distinguish network errors
    Toast.makeText(LoginActivity.this, "用户名/密码错误", Toast.LENGTH_LONG).show();
}
2. 登录成功后跳转至landing_page.xml对应的页面

First, make sure you have a LandingPageActivity that uses landing_page.xml as its layout. If you don't have it yet:

  • Right-click your package name → New → Activity → Empty Activity
  • Name it LandingPageActivity and select landing_page.xml as the layout file.

Then, replace the existing return/finish logic in onResponse with code to start the LandingPageActivity:

// Add this after saving user info to Constants
Intent intent = new Intent(LoginActivity.this, LandingPageActivity.class);
// Optional: Pass extra data to the landing page if needed
// intent.putExtra("username", Constants.username);
startActivity(intent);
// Close the login activity so users can't go back to it with the back button
finish();

Final Modified apiPostLogin Method

Here's the complete updated method for reference:

private void apiPostLogin(String data) {
    final ProgressDialog progress = new ProgressDialog(this);
    progress.setTitle("Logging in");
    progress.setMessage("Please wait ...");
    progress.setCancelable(false);
    progress.show();

    Call<ResponseBody> call = getRestClient().getLoginService().postLogin(data);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            progress.dismiss();
            if (response.isSuccessful() && response.body() != null) {
                try {
                    String data = response.body().string();
                    JSONObject jsonObject = new JSONObject(data);
                    
                    if (jsonObject.has("error") || jsonObject.getString("id").isEmpty()) {
                        Toast.makeText(LoginActivity.this, "用户名/密码错误", Toast.LENGTH_LONG).show();
                        return;
                    }

                    Constants.uid = Integer.parseInt(jsonObject.getString("id"));
                    Constants.username = jsonObject.getString("username");
                    Constants.email = jsonObject.getString("email");
                    Constants.credit = jsonObject.getString("credit");
                    Constants.qr_code = jsonObject.getString("qr_code");
                    Constants.created_at = jsonObject.getString("created_at");
                    Constants.updated_at = jsonObject.getString("updated_at");

                    // Jump to landing page
                    Intent intent = new Intent(LoginActivity.this, LandingPageActivity.class);
                    startActivity(intent);
                    finish();

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this, "登录失败,请重试", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(LoginActivity.this, "用户名/密码错误", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            progress.dismiss();
            Toast.makeText(LoginActivity.this, "用户名/密码错误", Toast.LENGTH_LONG).show();
        }
    });
}

内容的提问来源于stack exchange,提问作者Stormyq

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:35:57