[英]how to keep the response.body() data of Retrofit onRespose() call in a singleton
我尝试使用改造在网络调用期间存储来自response.body()
的数据。 但是我无法使用单例对象访问数据。
这是我的单例课程代码:
public class FishCategory {
private SparseArray<String> sparseArray = new SparseArray<>(3);
private static FishCategory singleton;
public static FishCategory getSingleton() {
if (singleton == null) {
singleton = new FishCategory();
}
return singleton;
}
public SparseArray<String> getSparse() {
ApiService service = ApiClient.getClient().create(ApiService.class);
Call<CategoryResp> call = service.categoryAPI();
call.enqueue(new Callback<CategoryResp>() {
@Override
public void onResponse(Call<CategoryResp> call, Response<CategoryResp> response) {
CategoryResp categoryResp = response.body();
for (int i = 0; i < categoryResp.getsData().getCategoryList().size(); i++) {
sparseArray.put(i, categoryResp.getsData().getCategoryList().get(i).getCatTitle());
}
}
@Override
public void onFailure(Call<CategoryResp> call, Throwable t) {
}
});
return sparseArray;
}
}
现在,如果我在其他类中使用此单例对象,它将返回null。 请帮忙....
public SparseArray<String> getSparse() {
ApiService service = ApiClient.getClient().create(ApiService.class);
Call<CategoryResp> call = service.categoryAPI();
call.enqueue(new Callback<CategoryResp>() {
@Override
public void onResponse(Call<CategoryResp> call, Response<CategoryResp> response) {
CategoryResp categoryResp = response.body();
for (int i = 0; i < categoryResp.getsData().getCategoryList().size(); i++) {
sparseArray.put(i, categoryResp.getsData().getCategoryList().get(i).getCatTitle());
}
}
@Override
public void onFailure(Call<CategoryResp> call, Throwable t) {
}
});
return sparseArray;
}
在这种情况下,您不是在创建非阻塞式编码,而是使用enqueue
方法将其转移到一个单独的线程中,同时您的代码仍在执行,这显然不会等待您的代码执行。因此,您的sparseArray为null。 请使用以下内容阻止自然,并注意以下内容将在Main UI线程上工作,这将引发异常。
TaskService taskService = ServiceGenerator.createService(TaskService.class);
Call<List<Task>> call = taskService.getTasks();
List<Task>> tasks = call.execute().body();
阅读以下内容以了解同步和异步性质。 https://futurestud.io/tutorials/retrofit-synchronous-and-asynchronous-requests
public SparseArray<String> getSparse() {
ApiService service = ApiClient.getClient().create(ApiService.class);
Call<CategoryResp> call = service.categoryAPI();
call.execute().body();
for( i = 0; i < categoryResp.getsData().getCategoryList().size(); i++) {
sparseArray.put(i, categoryResp.getsData().getCategoryList().get(i).getCatTitle());
}
return sparseArray;
}
我正在使用SharedPreferences
以及Retrofit
异步调用,问题已解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.