Search code examples
javaandroidretrofit

How to pass sharedpreferences value with url?


Hi i want to pass sharedpreferences value (ex:user id saved in shared pref)URL in api interface android or is there any way to do that.i am new to programming

 @FormUrlEncoded
    @POST("user.php/**{user_id}**")
    Call<UpdateUserResponse> sentUserUpdateddata(
            @Field("first_name") String first_name,
            @Field("last_name") String last_name,
            @Field("email") String email,
            @Field("password") String password,
            @Field("user_id") String user_id
    );

I dont have any idea about how to do this


Solution

  • Retrieve the user ID from SharedPreferences:

       SharedPreferences sharedPreferences = getSharedPreferences("YOUR_PREF_NAME", Context.MODE_PRIVATE);
    String userId = sharedPreferences.getString("user_id", "");
    

    Update your API interface to use @Path instead of @Field for the user ID:

    @FormUrlEncoded
    @POST("user.php/**{user_id}**")
    Call<UpdateUserResponse> sentUserUpdateddata(
            @Field("first_name") String first_name,
            @Field("last_name") String last_name,
            @Field("email") String email,
            @Field("password") String password,
            @path("user_id") String user_id
    );
    

    When making the API call, pass the retrieved user ID as an argument:

        Call<UpdateUserResponse> call = yourApiService.sentUserUpdatedData(firstName, lastName, email, password, userId);
    call.enqueue(new Callback<UpdateUserResponse>() {
        // Handle the response
        // ...
    });