Tags
Android
Asked 3 years ago
26 Sep 2021
Views 4143
Connor

Connor posted

java.lang.NullPointerException: Attempt to invoke virtual method java.lang.Object android.content.Context.getSystemService(java.lang.String) on a null object reference

code

 mPager.setAdapter(new SliderAdapter(getActivity(), sliderArraylist));
                            indicator.setViewPager(mPager);

Error :

    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
        at android.view.LayoutInflater.from(LayoutInflater.java:232)
        at com.example.adapter.SliderAdapter.<init>(SliderAdapter.java:35)
        at com.example.fragment.HomeFragment$4.onSuccess(HomeFragment.java:276)
        at com.loopj.android.http.JsonHttpResponseHandler$1$1.run(JsonHttpResponseHandler.java:152)
        at android.os.Handler.handleCallback(Handler.java:754)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:163)
        at android.app.ActivityThread.main(ActivityThread.java:6238)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
lain

lain
answered Sep 26 '21 00:00

you getting null object reference because getActivity() is null so you should check getActivity() !=null before use getActivity() so following code should solve the problem


if(getActivity()!=null){
 mPager.setAdapter(new SliderAdapter(getActivity(), sliderArraylist));
                            indicator.setViewPager(mPager);
}
Post Answer