我非常感兴趣为什么onResponse setter的方法效果不好。这是来自我的自定义类的方法,它负责从服务器获取响应。我注意到我想让它像我的代码一样异步。
public void setListItem(ArrayList<Item> listItem) {
this.listItem = listItem;
}
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();
setListItem(generateData(movieList));
}
@Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Toast.makeText(context, "ERROR", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
private ArrayList<Item> generateData(List<Movie> list){
listItem =new ArrayList<Item>();
for(int i=0;i<list.size();i++){
String title = list.get(i).getOriginalTitle();
String overview = list.get(i).getOverview();
String date = list.get(i).getReleaseDate();
float rate = list.get(i).getVoteAverage();
listItem.add(new Item(title,overview,date,rate));
}
return listItem;
}
这种我尝试在Activity中获取变量的方式,每次调试时都是null。
presenter = new Presenter(this,movie);
presenter.responseFromServer();
ArrayList<Item> item = presenter.getListItem();