JAVA获取response返回数据_java – 如何从Retrofit onResponse返回方法中的数据?
我是改装的新手,我想让我的getData方法返回一个功能对象.最简单的方法是什么?DataService.javapublic class DataService {private static final String TAG = MainActivity.class.getSimpleName();private final ApiClient apiClient;public DataSer
我是改装的新手,我想让我的getData方法返回一个功能对象.最简单的方法是什么?
DataService.java
public class DataService {
private static final String TAG = MainActivity.class.getSimpleName();
private final ApiClient apiClient;
public DataService() {
apiClient = new ApiClientFactory().createApiClient();
}
public List getData(){
apiClient.getData().enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
List features = response.body().getFeatures();
Log.d(TAG, "Data successfully downloaded");
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e(TAG, t.toString());
}
});
//I need to return features in getData method
}
}
解决方法:
你不能回来,你必须“回电”.
将内部Callback类提取为参数.
public void getData(Callback callback){
apiClient.getData().enqueue(callback);
}
在你的其他代码中
// DataService service = ...;
// Define Callback
Callback responseCallback = new Callback() {
@Override
public void onResponse(Call call, Response response) {
List features = response.body().getFeatures();
Log.d(TAG, "Data successfully downloaded");
// Data is returned here
for (Feature f: features) {
Log.d("feature", String.valueOf(f)); // for example
}
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e(TAG, t.toString());
}
};
// Call it
service.getData(responseCallback);
你也可以做service.getData(new Callback< DataResponse>(){…});
标签:java,android,retrofit2
来源: https://codeday.me/bug/20190522/1154430.html
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)