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

如何将SharedPreference存储的邮箱传入Retrofit作为API请求参数

Solution: Fetch User Settings Using Email from SharedPreferences

Let's break this down into simple, actionable steps to get your code working correctly:

1. Fix Your API Interface Definition

First, notice your current API method is expecting a phoneNumber field, but we need to send the user's email as the parameter to fetch their settings. Update your API.java like this:

public interface API {
    String BASE_URL = "http://base-url.com/";
    
    // Changed the @Field key to "email" since we're sending the user's email
    @FormUrlEncoded
    @POST("api/user/settings")
    Call<UserSetModel> getUserSettings(@Field("email") String userEmail);
}

2. Retrieve the User's Email from SharedPreferences

Since you mentioned UserPreferences already has methods to store/retrieve user info, just call its getter method for the email. For example, if your UserPreferences has a method like getUserEmail(), use it in MainActivity:

// Get the stored email from UserPreferences
String userEmail = UserPreferences.getInstance(this).getUserEmail();

Note: Make sure to handle cases where the email might be null (e.g., user hasn't signed in yet) to avoid crashes.

3. Execute the Retrofit Request with the Email Parameter

Now plug this email into your Retrofit request in MainActivity. Here's how the full request flow would look:

// Initialize Retrofit (assuming you already have this set up)
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(API.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

API apiService = retrofit.create(API.class);

// Get the email from SharedPreferences
String userEmail = UserPreferences.getInstance(this).getUserEmail();

if (userEmail != null && !userEmail.isEmpty()) {
    // Execute the request with the email parameter
    Call<UserSetModel> call = apiService.getUserSettings(userEmail);
    call.enqueue(new Callback<UserSetModel>() {
        @Override
        public void onResponse(Call<UserSetModel> call, Response<UserSetModel> response) {
            if (response.isSuccessful() && response.body() != null) {
                // Get the phone number from the response model
                String userPhoneNumber = response.body().getPhoneNumber();
                // Do something with the phone number (e.g., display it, store it)
                Log.d("MainActivity", "User Phone Number: " + userPhoneNumber);
            } else {
                // Handle unsuccessful response
                Log.e("MainActivity", "Failed to fetch settings: " + response.message());
            }
        }

        @Override
        public void onFailure(Call<UserSetModel> call, Throwable t) {
            // Handle network failure
            Log.e("MainActivity", "Network error: " + t.getMessage());
        }
    });
} else {
    // Handle case where email is not available (user not signed in)
    Toast.makeText(this, "User not signed in", Toast.LENGTH_SHORT).show();
}

4. Verify Your UserSetModel

Double-check that your UserSetModel.java has the correct getter method for phoneNumber, like:

public class UserSetModel {
    private String userID;
    private String userName;
    private String email;
    private String phoneNumber;

    // Constructor, setter methods...

    public String getPhoneNumber() {
        return phoneNumber;
    }
}

That's it! This flow will:

  • Pull the user's email from SharedPreferences
  • Send it as a parameter to your API endpoint
  • Retrieve the user's settings (including phone number) from the response

内容的提问来源于stack exchange,提问作者T-lang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:20:04