尝试调用虚方法-FAILURE:App崩溃

时间:2017-12-01 13:47:00

标签: java android retrofit

在尝试运行该应用时,它会崩溃并说"Attempt to invoke virtual method"。以下是logcat中发现的错误。

FATAL EXCEPTION: main
    Process: com.example.sayantan.moviebugs, PID: 1694
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.sayantan.moviebugs.model.MoviesResponse.getResults()' on a null object reference
            at com.example.sayantan.moviebugs.MainActivity$2.onResponse(MainActivity.java:132)
            at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:168)
            at android.app.ActivityThread.main(ActivityThread.java:5885)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)

以下是main_activity.java文件中的Json代码段:

eCall<MoviesResponse> call = apiService.getPopularMovies(BuildConfig.THE_MOVIE_DB_API_TOKEN);
        call.enqueue(new Callback<MoviesResponse>() {
            @Override
            public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) {
                List<Movie> movies = response.body().getResults();

                //Collections.sort(movies, Movie.BY_NAME_ALPHABETICAL);
                recyclerView.setAdapter(new MoviesAdapter(getApplicationContext(), movies));
                recyclerView.smoothScrollToPosition(0);
                if (swipeContainer.isRefreshing()){
                    swipeContainer.setRefreshing(false);
                }

以下是模型文件的片段:

  public void setPage(int page) {
    this.page = page;
}

public List<Movie> getResults()
{
    return results;
}

public List<Movie> getMovies() {
    return results;
}

public void setResults(List<Movie> results) {
    this.results = results;
}

1 个答案:

答案 0 :(得分:2)

当有响应时,会调用Retrofit onResponse,这意味着当出现错误时也会调用它。在这种情况下,body(getBody())为null,如果您尝试使用它,将导致java.lang.NullPointerException。

如何在您的案例中使用Retrofit的示例:

Gradle Sync Failed