[英]Android Retrofit Call pass response.body() as paramater for processing
我想知道如何將 response.body() 作為參數傳遞以進一步處理它。 因為現在我只能將它傳遞給 Toast 或 textView 的 setText,它工作得很好。 但是,如果我嘗試將它傳遞給 function 將其保存到 SharedPrefs 或類似的東西,它只會傳遞 null object。 我不明白為什么第一個有效,但第二個無效,區別在哪里?
我的 JSon 響應體如下所示:
{
"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkBhZG1vbi5jb20iLCJleHAiOjE1OTQ2NTQ0NjF9.4meOycRP4wbx6hVCJntxH71E03jMYJhg484zCGInUDh6EKPPVDlOhEkCC3X2mjPaCHVfT0qhiulBnC39uh4WEQ"
}
我的 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;
}
}
我進行呼叫的 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();
}
}
}
任何幫助將不勝感激。 提前致謝!
你忘了打電話editor.apply();
或editor.commit();
為了保存更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.