0

Hello I have a problem with getter in my custom class, I don't know why it returns null every time. I'm setting value after response from server when it is without any errors. While I'm debugging, I see that response from server is OK and new instance of my object is created but when I try to get it in my activity there is a null. Here is couple lines of code where is a problem (in my opinion).

method from my custom class:

 public void responseFromServer(){
    showProgressDialog();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
    TitleInterface titleInterface = retrofit.create(TitleInterface.class);
    Call<MovieResponse> call = titleInterface.getMovie(API_KEY,movie);
    call.enqueue(new Callback<MovieResponse>() {
        @Override
        public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
            List<Movie> movieList =  response.body().getMovieList();
            ItemAdapter itemAdapter = new ItemAdapter(context.getApplicationContext(),generateData(movieList));
            setItemAdapter(itemAdapter);
        }

        @Override
        public void onFailure(Call<MovieResponse> call, Throwable t) {
            Toast.makeText(context, "ERROR", Toast.LENGTH_SHORT).show();
            progressDialog.dismiss();
        }
    });
}

and here is my Activity:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_movie_list);

    movieListView = (ListView) findViewById(R.id.movieListView);
    String movie = getIntent().getStringExtra(TAG);

    presenter = new Presenter(this,movie);
    presenter.responseFromServer();
    item=presenter.getItemAdapter();
    movieListView.setAdapter(presenter.getItemAdapter());
    presenter.getItemAdapter().notifyDataSetChanged();
    presenter.getProgressDialog().dismiss();
}

Thanks for any help.

stuck
  • 1,477
  • 2
  • 14
  • 30

2 Answers2

0

It seems like your request haven't finished when the view is created. If you want to make your call synchronous use this:

Call<MovieResponse> call = titleInterface.getMovie(API_KEY,movie);
Response<MovieResponse> responseBody = call.execute();

List<Movie> movieList =  response.body().getMovieList();
Jaythaking
  • 2,200
  • 4
  • 25
  • 67
0

You are using asynchronous calls in your app, so try to replace all necessary methods for updating UI from onCreate() to onResponse(). It should help. If you want to use Retrofit synchronous calls, the best practice for that is Loaders.