use*_*928 3 java oop android retrofit retrofit2
我正在尝试使用用于发送回服务器的 Retrofit 调用从标头中检索某个字段的值。我成功地获取了 try 块中的值并立即在 try 块中将其发送回。但是当我在调用实例之外尝试相同的操作时,abc 的值(这是我分配响应头的值的地方)丢失了。我已经将字符串 abc 声明为全局变量。如何保存字符串的值?
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "MainActivityClass";
String abc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<TrendingModel>> call = apiService.getAllTodos();
call.enqueue(new Callback<List<TrendingModel>>() {
@Override
public void onResponse(Call<List<TrendingModel>> call, Response<List<TrendingModel>> response) {
try {
List<TrendingModel> todoModels = response.body(); // WHERE WE GET THE RESPONSE BODY
abc = response.headers().get("Tanand"); // WHERE WE GET THE RESPONSE HEADER AND ASSIGN IT TO abc, WHICH WE DECLARED GLOBALLY
ApiClient.getClient(abc).create(ApiInterface.class); // PASSING THE abc VARIABLE TO THE GETCLIENT(TOKEN) METHOD WITHIN
// THE SAME TRY BLOCK WHICH WORKDS
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
@Override
public void onFailure(Call<List<TrendingModel>> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});
ApiClient.getClient(abc).create(ApiInterface.class); // VALUE OF abc IS NOT PERSISTED HERE (abc IS NULL) ALTHOUGH WE DECLARED IT GLOBALLY
}
}
Run Code Online (Sandbox Code Playgroud)
尝试在 OnResponse 方法中调用方法。
因为onResponse()方法在后台运行,直到获取数据。
如果您想访问响应数据,请在其中调用您的方法。
而以外的所有声明之前,被称为完成响应数据这就是为什么它不给你实际的数据。作为一种良好做法,请使用以下方法。
只需在类中创建一个方法并在其中调用所有语句。
现在在 onResponse 方法中调用您的方法。
| 归档时间: |
|
| 查看次数: |
3482 次 |
| 最近记录: |