Android Retrofit Call pass response.body() as paramater for processing

Tags: , ,



I’m wondering how to pass the response.body() as paramater in order to further process it. Since now i could pass it only to a Toast, or setText of a textView, and it works just fine. But if i try to pass it to a function which saves it to SharedPrefs or something like it just passes a null object. I don’t get the point why the first is working, but the second not, where’s the difference?

My JSon response body looks like this:

{
    "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkBhZG1vbi5jb20iLCJleHAiOjE1OTQ2NTQ0NjF9.4meOycRP4wbx6hVCJntxH71E03jMYJhg484zCGInUDh6EKPPVDlOhEkCC3X2mjPaCHVfT0qhiulBnC39uh4WEQ"
}

My Pojo like this:

public class LoginResponse {

    @Expose
    @SerializedName("Authorization")
    private String authToken;

    public LoginResponse(String authToken) {
        this.authToken = authToken;
    }


    public void setAuthToken(String authToken) {
        this.authToken = authToken;
    }

    public String getAuthToken() {
        return authToken;
    }
}

The function where I do the Call (it’s called after hitting the login button):

private void loginCustomer() {
        LoginRequest loginRequest = new LoginRequest(editTextUsername.getText().toString(), editTextPassword.getText().toString());

        Call<LoginResponse> loginCall = ApiUtils.getApi().login(loginRequest);
        loginCall.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(@NotNull Call<LoginResponse> call, @NotNull Response<LoginResponse> response) {
                if (!response.isSuccessful()) {
                    Toast.makeText(LoginActivity.this, "User Credentials Wrong", Toast.LENGTH_SHORT).show();
                } else {
                    if (response.body() != null) {

// this does not work
                        authToken = response.body().getAuthToken();
                        saveToken(authToken);

 //this does not work either                       SharedPreferences.Editor editor = sp.edit();
                        editor.putString("authToken", response.body().getAuthToken());

//                        openUserMainActivity();
// this works                        Toast.makeText(LoginActivity.this, response.code() + " " + response.body().getAuthToken(), Toast.LENGTH_SHORT).show();
// this does not work                        Toast.makeText(LoginActivity.this, sp.getString("authToken", "no token"), Toast.LENGTH_SHORT).show();

                    }


                }
            }

Any help will be appreciated. Thanks in Advance!

Answer

You forgot to call editor.apply(); or editor.commit(); in order to save the changes.



Source: stackoverflow