2016-11-22 1 views
1

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(); 
} 
내가 다음 방법 같은 조각의 요청을 호출하고있어

:

콜백은 UI를 업데이트 할 데이터가 때까지 기다릴 수있는 방법
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; 
    } 

    ... 

} 

? 고맙습니다.

+0

하지만 그때까지 메인 스레드를 차단합니다. 비동기 요청을 만들어야하고 응답을 받으면 UI를 업데이트하십시오. – nandsito

답변

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 
    } 
} 
+0

얼마나 바보입니까? 감사합니다. – MAOL

+0

getVideos 메소드에 콜백을 전달해야합니다. – MAOL

+0

예, 프래그먼트가 콜백을 구현했기 때문에 프래그먼트를 메소드 '일명'에 전달합니다. –