2016-11-22 35 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(); 
} 

我打電話從片段喜歡下方式請求:

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

同步請求將自動等待響應,但它會阻止主線程直到那時。你應該做一個異步請求,並在收到響應後,更新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

是的,並且由於您的片段實現了回調,所以您將片段傳遞給方法aka'this'。 –