尝试访问API时发生空指针异常

我只是尝试retrofit2为我目前正在处理的新闻应用程序,我试图在片段类中调用我的API实现。 但我一直得到nullpointerexception,这是我的片段代码:

public class IgnFragment extends Fragment {


@BindView(R.id.ignNewsContainer)
RecyclerView ignNewsContainer;
Unbinder unbinder;

Call<NewsArticle> call;
public IgnFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_ign, container, false);
    unbinder = ButterKnife.bind(this, view);
    return view;

}

@Override
public void onStart() {
    super.onStart();
     call = NewsApi.getApi().getArticles("ign", "top");
    getClient();
}
public void getClient(){
    call.enqueue(new Callback<NewsArticle>() {
        @Override
        public void onResponse(Call<NewsArticle> call, Response<NewsArticle> response) {
            NewsArticle newsArticle = response.body();
            NewsAdapter newsAdapter = new NewsAdapter(newsArticle.getArticles(),getContext());
            ignNewsContainer.setAdapter(newsAdapter);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            ignNewsContainer.setLayoutManager(linearLayoutManager);
        }

        @Override
        public void onFailure(Call<NewsArticle> call, Throwable t) {
            t.printStackTrace();
            Log.e("Error","Called");
        }
    });
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    unbinder.unbind();
}

这里是我的api服务类:

public class NewsApi {
private static final String API_KEY = "________";
private static final String URL_BASE ="https://newsapi.org/v1/";


private static NewsService newsService =null;
public static NewsService getApi(){
   if(newsService == null){
       Retrofit retrofit= new Retrofit.Builder()
               .baseUrl(URL_BASE)
               .addConverterFactory(GsonConverterFactory.create())
               .client(getClient())
               .build();
        NewsService api = retrofit.create(NewsService.class);
   }
    return newsService;
}

public static OkHttpClient getClient(){
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    return  httpClient.addInterceptor(logging).build();
}

public interface  NewsService{
    @GET("articles?apiKey=" + API_KEY)
    Call<NewsArticle> getArticles(@Query("source") String source,@Query("sortBy") String sortBy);
}

}

这是我得到的错误:

10-30 20:42:01.640 32640-32640 / cc.codemonkey.newsportal E / AndroidRuntime:致命异常:主进程:cc.codemonkey.newsportal,PID:32640 java.lang.NullPointerException:试图调用接口方法'retrofit2。调用cc.codemonkey.newsportal.fragments.IgnFragment.onStart上的空对象引用cc.codemonkey.newsportal.service.NewsApi $ NewsService.getArticles(java.lang.String,java.lang.String)'(IgnFragment.java: 54)at android.support.v4.app.Fragment.performStart(Fragment.java:2265)at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1369)at android.support.v4.app.FragmentManagerImpl .moveFragmentToExpectedState(FragmentManager.java:1574)在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)在android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)在android。 support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)at android.support.v4.app.FragmentManagerImpl.executeOpsTogether( FragmentManager.java:2200)at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2034)at android.support.v4 .app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:651)在android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)在android.support.v4.view.ViewPager.populate(ViewPager.java:1239 )在android.view.View.get.ViewPager.onMeasure(ViewPager.java:1613)android.view.View.measure(View。)上的android.support.v4.view.ViewPager.populate(ViewPager.java:1087)的java:17442)在android.widget.RelativeLayout.measureChildHorizo​​ntal(RelativeLayout.java:727)在android.widget.RelativeLayout.onMeasure(RelativeLayout.java:463)在android.view.View.measure(View.java:17442)在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)at android.support.v7.widg et.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)在android.view.View.measure(View.java:17442)在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)在android.widget.LinearLayout.measureChildBeforeLayout (LinearLayout.java:1436)at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)at android.view.View.measure(View.java: (android.view.java:17442)android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)在android.widget.FrameLayout.onMeasure(FrameLayout.java:430)在android.view.View.measure(View.java:17442)。 view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)在android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)在android.widget.LinearLayout.measureVertical(LinearLayout.java:722)在android.widget.LinearLayout.onMeasure (LinearLayout.java:613)at android.view.View.measure(View.java:17442)at android.view.ViewGroup.measureChildWithMargins(Vi ewGroup.java:5463)at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)at com.android.internal.policy.impl.PhoneWindow $ DecorView.onMeasure(PhoneWindow.java:2560)at android.view.View .measure(View.java:17442)在android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)在android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)在android.view.ViewRootImpl.performTraversals(ViewRootImpl。 Java的:1372)在android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)在android.view.ViewRootImpl $ TraversalRunnable.run(ViewRootImpl.java:5779)在android.view.Choreographer $ CallbackRecord.run(Choreographer.java :767)at android.view.Choreographer.doCallbacks(Choreographer.java:580)at android.view.Choreographer.doFrame(Choreographer.java:550)at android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:753) android.os.Handler.handleCallback(Handler.java:739)在android.os.Handler.dispatchMessage(Handler.java:95)android.os.Looper.loop(Looper.java: 135)at android.app.ActivityThread.main(ActivityThread.java:5253)at java.lang。


你的问题是在这个确切的路线

NewsAdapter newsAdapter = new NewsAdapter(newsArticle.getArticles(),getContext());

问题说新闻文章在这里已经初始化为null

NewsArticle newsArticle = response.body();

所以response.body()为null请尝试调试,并看看它为什么是空的! 当你解决这个问题时你的解决方案应该可以工 而且alos指的是什么是NullPointerException,我该如何解决它? 了解更多NullPointerException是什么。

链接地址: http://www.djcxy.com/p/93049.html

上一篇: Null pointer exception when try to access API

下一篇: Google map inflate exception