如何将 Retrofit onRespose() 调用的 response.body() 数据保存在单例中



我试图使用改造在网络呼叫期间存储来自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,您可以在代码仍在执行时将其转移到单独的线程,这显然不会等待代码执行。所以你的稀疏数组是空的。 请在下面使用阻止性质,并注意下面的将处理会引发异常的主 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并且问题已解决。

最新更新