我正在尝试使用Retrofit和OkHttp向服务器发出请求。我有下一个类“AutomaticRequest.java”,它要求从服务器获取视频。
public class AutomaticRequest {
public void getVideos(final AutomaticCallback callback){
MediaproApiInterface service = ApiClient.getClient();
Call<List<AutomaticVideo>> call = service.getAllVideos();
call.enqueue(new Callback<List<AutomaticVideo>>() {
@Override
public void onResponse(Call<List<AutomaticVideo>> call, Response<List<AutomaticVideo>> response) {
List<AutomaticVideo> automaticVideoList = response.body();
callback.onSuccessGettingVideos(automaticVideoList);
}
@Override
public void onFailure(Call<List<AutomaticVideo>> call, Throwable t) {
callback.onError();
}
});
}
}
我创建了下一个类“AutomaticCallback.java”来检索数据。
public interface AutomaticCallback {
void onSuccessGettingVideos(List<AutomaticVideo> automaticVideoList);
void onError();
}
我正在通过下一个方式调用片段中的请求:
public class AllVideosFragment extends Fragment {
...
AutomaticCallback callback;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_allvideos, container, false);
new AutomaticRequest().getVideos(callback);
return view;
}
...
}
我怎么能等到回调有数据来更新UI?谢谢。
答案 0 :(得分:2)
只需在片段上实现AutomaticCallback接口,如:
public class AllVideosFragment extends Fragment implements AutomaticCallback {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_allvideos, container, false);
new AutomaticRequest().getVideos(this);
return view;
}
@Override
void onSuccessGettingVideos(List<AutomaticVideo> automaticVideoList){
// use your data here
}
@Override
void onError(){
// handle the error
}
}