Null pointer exception when try to access API
I just tried retrofit2 for my news app that I am currently working on, I tried to call my API implementation in a fragment class. But I keep getting nullpointerexception, here's my fragment code:
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();
}
and here is my api service class:
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);
}
}
and here's the error I get:
10-30 20:42:01.640 32640-32640/cc.codemonkey.newsportal E/AndroidRuntime: FATAL EXCEPTION: main Process: cc.codemonkey.newsportal, PID: 32640 java.lang.NullPointerException: Attempt to invoke interface method 'retrofit2.Call cc.codemonkey.newsportal.service.NewsApi$NewsService.getArticles(java.lang.String, java.lang.String)' on a null object reference at cc.codemonkey.newsportal.fragments.IgnFragment.onStart(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) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641) at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794) at 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) at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143) at android.support.v4.view.ViewPager.populate(ViewPager.java:1239) at android.support.v4.view.ViewPager.populate(ViewPager.java:1087) at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1613) at android.view.View.measure(View.java:17442) at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:727) at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:463) at android.view.View.measure(View.java:17442) at 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) at android.view.View.measure(View.java:17442) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at 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:17442) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.FrameLayout.onMeasure(FrameLayout.java:430) at android.view.View.measure(View.java:17442) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at 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: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) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779) at 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) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java: 135) at android.app.ActivityThread.main(ActivityThread.java:5253) at java.lang.
Your problem is at this exact line
NewsAdapter newsAdapter = new NewsAdapter(newsArticle.getArticles(),getContext());
the problem says that the newsArticle is being null
which has been initialized here
NewsArticle newsArticle = response.body();
so response.body()
is null please try to debug and to see why is it empty! when you fix this your solution should work. And alos refer to this What is a NullPointerException, and how do I fix it? to understand more what a NullPointerException is.
上一篇: android上的setFilterMap是做什么的?
下一篇: 尝试访问API时发生空指针异常