我正在开发一款Android应用,可以显示最受好评的电影的电影海报。我想通过使用Retrofit 2来构建它。但是,我不断收到错误'服务方法无法返回void'。这是堆栈跟踪:
FATAL EXCEPTION: main
Process: com.hfad.popularmovies, PID: 17921
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hfad.popularmovies/com.hfad.popularmovies.MainActivity}: java.lang.IllegalArgumentException: Service methods cannot return void.
for method MoviesAPI.getFeedPopular
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalArgumentException: Service methods cannot return void.
我创建了一个包含我需要的字段的POJO&包含get request =>的必要接口
public interface MoviesAPI {
@GET("/movie/top_rated?api_key=XXXXXXX")
void getFeedTopRated(Callback <List<Movie>> response);
@GET("/movie/popular?api_key=XXXXXXX")
void getFeedPopular(Callback<List<Movie>> response);
}
这是应该通过RecyclerView显示海报的片段:
public class TopRatedFragment extends Fragment {
private static final String ENDPOINT = "http://api.themoviedb.org/3/";
private PosterAdapter adapter;
private List<Movie> movieList;
public TopRatedFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.fragment_top_rated, container, false);
adapter = new PosterAdapter(getActivity());
recyclerView.setAdapter(adapter);
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(layoutManager);
getTopRatedMovies();
return recyclerView;
}
private void getTopRatedMovies() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ENDPOINT)
.build();
MoviesAPI api = retrofit.create(MoviesAPI.class);
api.getFeedTopRated(new Callback<List<Movie>>() {
@Override
public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
movieList = response.body();
for (Movie movie : movieList) {
movie.getPoster_path(); //I get the same error when I use
}
}
@Override
public void onFailure(Call<List<Movie>> call, Throwable t) {
}
});
}
}
请告诉我是否应提供更多代码或背景信息。
答案 0 :(得分:1)
您的接口方法需要从类型
返回一个对象Call<Expected Result Object>
例如
@GET("/movie/top_rated?api_key=XXXXXXX")
Call<List<Movie>> getFeedTopRated();
在方法中,您需要编写如下函数:
api.getFeedTopRated().enque(new Callback<List<Movie>>() { /* */ });