[英]Android Retrofit Call pass response.body() as paramater for processing
I'm wondering how to pass the response.body() as paramater in order to further process it.我想知道如何将 response.body() 作为参数传递以进一步处理它。 Since now i could pass it only to a Toast, or setText of a textView, and it works just fine.
因为现在我只能将它传递给 Toast 或 textView 的 setText,它工作得很好。 But if i try to pass it to a function which saves it to SharedPrefs or something like it just passes a null object.
但是,如果我尝试将它传递给 function 将其保存到 SharedPrefs 或类似的东西,它只会传递 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:我的 JSon 响应体如下所示:
{
"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkBhZG1vbi5jb20iLCJleHAiOjE1OTQ2NTQ0NjF9.4meOycRP4wbx6hVCJntxH71E03jMYJhg484zCGInUDh6EKPPVDlOhEkCC3X2mjPaCHVfT0qhiulBnC39uh4WEQ"
}
My Pojo like this:我的 Pojo 是这样的:
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):我进行呼叫的 function (在点击登录按钮后调用):
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!
提前致谢!
You forgot to call editor.apply();
你忘了打电话
editor.apply();
or editor.commit();
或
editor.commit();
in order to save the changes.为了保存更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.