The response from the retrofit call is too slow and it returns a null list

最后都变了- 提交于 2019-12-27 01:19:18

问题


Getting response as null in onResponse(). How to improve time duration for response?

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;
}


}

Anyone can help me with a solution to get the list after onResponse method. The duration of the onResponse method has about 400 ms. This is the part of the code where I need the list:

@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);
}

Thanks.


回答1:


I used ReactiveX to solve the problem. Another solution was a callback from onResponse() method.

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


来源:https://stackoverflow.com/questions/46034047/the-response-from-the-retrofit-call-is-too-slow-and-it-returns-a-null-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!