【问题标题】:Retrofit using saved id in SharedPreference to POST update based on id使用 SharedPreference 中保存的 id 改造为基于 id 的 POST 更新
【发布时间】:2022-01-23 17:16:38
【问题描述】:

我有来自登录的用户 ID 保存在共享首选项中,我想通过将 POST 方法发送到 API 来更新个人资料,但出现错误:

属性值必须是常量

UserService.java:

   GetPrefId callid = new GetPrefId(); //this is the user id source(GetPrefId.java)

   @Headers("Content-Type: application/json")
   @POST("users/update/" + callid)
   Call<UpdateResponse> userUpdate(@Body UpdateRequest updateRequest);

GetPrefId.java:

public class GetPrefId extends AppCompatActivity {

        SharedPrefManager sharedPrefManager = new SharedPrefManager(this);
        private String idPref = sharedPrefManager.getId();

        public static final String prefid() {
                String id = GetPrefId.prefid();
                return id;
        }
}

API 端点:

apiendpoint.com/users/update/:id

:id 基于共享首选项中保存的 id

我不知道将用户 ID 插入 URL 的任何其他方法。感谢您的关注和帮助

更新:

这是 UpdateActivity 逻辑:

    UpdateRequest updateRequest = new UpdateRequest();
    updateRequest.setEmail(email.getText().toString());
    updateRequest.setUsername(username.getText().toString());
    updateRequest.setPassword(password.getText().toString());

    Call<UpdateResponse> updateResponseCall = ApiClient.getUserService().userUpdate(updateRequest);
    updateResponseCall.enqueue(new Callback<UpdateResponse>() {
        @Override
        public void onResponse(Call<UpdateResponse> call, Response<UpdateResponse> response) {

            if(response.isSuccessful()){
                Toast.makeText(EditprofilActivity.this,"Update Successful", Toast.LENGTH_LONG).show();
                UpdateResponse signupResponse =  response.body();

【问题讨论】:

    标签: java android retrofit retrofit2


    【解决方案1】:

    根据retrofit documentation 在 URL 中插入 id 这样做

    @GET("group/{id}/users")
    Call<List<User>> groupList(@Path("id") int groupId);`
    

    更新:

    根据您更新的问题,这样做:

    UpdateRequest updateRequest = new UpdateRequest();
    updateRequest.setEmail(email.getText().toString());
    updateRequest.setUsername(username.getText().toString());
    updateRequest.setPassword(password.getText().toString());
    
    //here get your id from sharedpref
    SharedPrefManager sharedPrefManager = new SharedPrefManager(this);
    private String idPref = sharedPrefManager.getId();
    
    //and pass the id to your api function
    Call<UpdateResponse> updateResponseCall = ApiClient.getUserService().userUpdate(idPref , updateRequest);
    
    

    【讨论】:

    • 我如何将 sharedpref id 传递给 te "id"?
    • 请检查我的更新活动,上面
    • @Dwictator 检查我的更新答案
    猜你喜欢
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多