我是改装的新手,我想让我的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