如何解决此错误Java.lang.NullPointerException:尝试调用虚拟方法'java.util.List

时间:2019-05-08 17:18:37

标签: java android xml android-studio

我需要将本文放入recyleview中,如何解决?我是新手

NewsResponse.java

 public class NewsResponse {
        @SerializedName("status")
        @Expose
        private String status;
        @SerializedName("totalResults")
        @Expose
        private List totalResults;
        @SerializedName("articles")
        @Expose

        private List<Article> articles = null;

        //get
        public String getStatus() {
            return status;
        }
        public List getTotalResults() {
            return totalResults;
        }
        public List<Article> getArticles() {
            return articles;
        }

MainActivity.java

  NewsApiService newsApiService = retrofit.create(NewsApiService.class);
            Call<NewsResponse> call = newsApiService.getNewsArticle(API_KEY);
            call.enqueue(new Callback<NewsResponse>() {
                @Override
                public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
                    List <Article> articles = response.body().getTotalResults();
                    recyclerView.setAdapter(new ArticleAdapter(articles, R.layout.list_item_article,
                            getApplicationContext()));
                    Log.d(TAG, "Total Artikel : " + articles.size());
                }

NewsApiService.java(接口)

public interface NewsApiService {
    @GET("/v2/top-headlines")
    Call<NewsResponse> getNewsArticle(@Query("api_key") String apiKey);
}

错误结果

  

E / Android运行时:致命异常:主要       流程:com.example.android.flashnews,PID:5277       java.lang.NullPointerException:尝试调用虚拟方法'java.util.List   com.example.android.flashnews.model.NewsResponse.getTotalResults()'   空对象引用           在com.example.android.flashnews.activity.MainActivity $ 1.onResponse(MainActivity.java:55)           在retrofit2.ExecutorCallAdapterFactory $ ExecutorCallbackCall $ 1 $ 1.run(ExecutorCallAdapterFactory.java:70)           在android.os.Handler.handleCallback(Handler.java:873)           在android.os.Handler.dispatchMessage(Handler.java:99)           在android.os.Looper.loop(Looper.java:193)           在android.app.ActivityThread.main(ActivityThread.java:6669)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:493)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)   I / Process:正在发送信号。 PID:5277 SIG:9应用程序终止。

0 个答案:

没有答案