2017-09-04 41 views
-3

在onResponse()中將響應設爲null。如何提高響應時間?來自改造呼叫的響應太慢,它返回空列表

public class RequestClass { 

private static final String TAG = RequestClass.class.getSimpleName(); 
private final static String API_KEY = "apikey"; 
static ApiInterface apiService = 
     ApiClient.getClient().create(ApiInterface.class); 

static public List<Movie> getTopMovies(String page) { 
    final List<Movie> lowDetailMovies = new ArrayList<Movie>(); 
    Call<MoviesResponse> call = apiService.getTopRatedMovies(API_KEY, page); 
    call.enqueue(new Callback<MoviesResponse>() { 
     @Override 
     public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) { 
      List<DBMovie> movies = response.body().getResults(); 

      for (DBMovie movie : movies) { 
       String[] genres = new String[6]; 
       int i = 0; 
       for (int gen : movie.getGenreIds()) 
        genres[i++] = gen + ""; 
       lowDetailMovies.add(new Movie(movie.getId(), Double.toString(movie.getVote_average()), movie.getTitle(), movie.getTitle(), movie.getPoster_path(), movie.getOriginal_language(), 
         movie.getOriginal_title(), genres, movie.getOverview(), movie.getRelease_date(), false, false)); 
      } 
     } 

     @Override 
     public void onFailure(Call<MoviesResponse> call, Throwable t) { 
      Log.e(TAG, t.toString()); 
     } 
    }); 


    return lowDetailMovies; 
} 


} 

任何人都可以通過解決方案來幫助我獲得onResponse方法後的列表。 onResponse方法的持續時間約爲400毫秒。 這是代碼的一部分,我需要的列表:

@OnClick(R.id.popular_button) 
public void showPopularMovies(View view) { 
    List<Movie> movies; 

    movies = RequestClass.getTopMovies("1"); 

    Intent intent = new Intent(MainActivity.this, VODActivity.class); 
    Collections.sort(movies, Util.compareByPopularityAscending); 

    Bundle bundle = new Bundle(); 
    bundle.putSerializable(Constants.bundleMovieKey, (Serializable) movies); 
    bundle.putString(Constants.bundleVodActivityTitle, Constants.PopularMoviesTitle); 
    intent.putExtras(bundle); 

    startActivity(intent); 
} 

謝謝。

+1

你爲什麼不從onResponse方法開始活動? – joao86

+0

,因爲onResponse()方法在另一個類中。 –

回答

0

我用ReactiveX解決了這個問題。另一個解決方案是從onResponse()方法的回調。

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); 
    apiService.getTopRatedMovies(Constants.API_KEY, Constants.FIRST_PAGE) 
      .subscribeOn(Schedulers.newThread()) 
      .observeOn(AndroidSchedulers.mainThread()) 
      .subscribe(popularMoviesSubscriber);