• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps on a null object reference

Attempt to invoke virtual method 'void com.yk.danaberkah._sliders.SliderView.setDurationScroll(int)'

  • Apps

    Votes: 2 100.0%
  • Answered

    Votes: 0 0.0%

  • Total voters
    2

Kurniawan

Newbie
Excuseme.. i hava promblem with my activity. how i fix on a null object reference. Thanks :)

Code:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.yk.danaberkah, PID: 22728
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yk.danaberkah/com.yk.danaberkah.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.yk.danaberkah._sliders.SliderView.setDurationScroll(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2363)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2426)
        at android.app.ActivityThread.access$800(ActivityThread.java:176)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1343)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.yk.danaberkah._sliders.SliderView.setDurationScroll(int)' on a null object reference
        at com.yk.danaberkah.MainActivity.setupSlider(MainActivity.java:162)
        at com.yk.danaberkah.MainActivity.onCreate(MainActivity.java:96)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2316)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2426)
        at android.app.ActivityThread.access$800(ActivityThread.java:176)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1343)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
Application terminated.


This My MainActivity.java


Java:
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
private SliderPagerAdapter mAdapter;
            private SliderIndicator mIndicator;
            private String TAG = MainActivity.class.getSimpleName();
            private SliderView sliderView;
            private LinearLayout mLinearLayout;

@Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    Toolbar toolbar = findViewById(R.id.toolbar);
                    setSupportActionBar(toolbar);
                    sliderView = (SliderView) findViewById(R.id.sliderView);
                    mLinearLayout = (LinearLayout) findViewById(R.id.pagesContainer);
                    setupSlider();

/*Slider Setup Example Use URLS*/
                private void setupSlider() {
                    sliderView.setDurationScroll(800);
                    List<Fragment> fragments = new ArrayList<>();
                    fragments.add(FragmentSlider.newInstance("https://jssorcdn7.azureedge.net/demos/img/gallery/980x380/001.jpg"));
                    fragments.add(FragmentSlider.newInstance("https://www.dnvgl.co.uk/Images/ISO2015-revisions-1134x350_tcm12-13061.jpg"));
                    fragments.add(FragmentSlider.newInstance("https://www.dnvgl.co.uk/Images/ISO2015-revisions-1134x350_tcm12-13061.jpg"));
                    fragments.add(FragmentSlider.newInstance("https://jssorcdn7.azureedge.net/demos/img/gallery/980x380/001.jpg"));

                    Log.e(TAG, "Response from fragment: " + sliderView);
                    mAdapter = new SliderPagerAdapter(getSupportFragmentManager(), fragments);
                    sliderView.setAdapter(mAdapter);
                    mIndicator = new SliderIndicator(this, mLinearLayout, sliderView, R.drawable.indicator_circle);
                    mIndicator.setPageCount(fragments.size());
                    mIndicator.show();
                }
      }
}

This FragmentSlider.java

Code:
public class FragmentSlider extends Fragment {

    private static final String ARG_PARAM1 = "params";

    private String imageUrls;

    public FragmentSlider() {
    }

    public static FragmentSlider newInstance(String params) {
        FragmentSlider fragment = new FragmentSlider();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, params);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        imageUrls = getArguments().getString(ARG_PARAM1);
        View view = inflater.inflate(R.layout.fragment_slider, container, false);
        ImageView img = (ImageView) view.findViewById(R.id.image_slider);
        Glide.with(getActivity())
                .load(imageUrls)
                .placeholder(R.drawable.beras_murah)
                .into(img);
        return view;
    }
}



This SliderIndicator.java

Java:
public class SliderIndicator implements ViewPager.OnPageChangeListener {
    private Context mContext;
    private LinearLayout mContainer;
    private int mDrawable;
    private int mSpacing;
    private int mSize;
    private ViewPager mViewPager;
    private int mPageCount;
    private int mInitialPage = 0;

    private int defaultSizeInDp = 12;
    private int defaultSpacingInDp = 12;

    public SliderIndicator(@NonNull Context context,
                           @NonNull LinearLayout containerView,
                           @NonNull ViewPager viewPager,
                           @DrawableRes int drawableRes) {
        if (context == null) {
            throw new IllegalArgumentException("context cannot be null");
        } else if (containerView == null) {
            throw new IllegalArgumentException("containerView cannot be null");
        } else if (viewPager == null) {
            throw new IllegalArgumentException("ViewPager cannot be null");
        } else if (viewPager.getAdapter() == null) {
            throw new IllegalArgumentException("ViewPager does not have an adapter set on it.");
        }
        mContext = context;
        mContainer = containerView;
        mDrawable = drawableRes;
        mViewPager = viewPager;

    }

    public void setPageCount(int pageCount) {
        mPageCount = pageCount;
    }

    public void setInitialPage(int page) {
        mInitialPage = page;
    }

    public void setDrawable(@DrawableRes int drawable) {
        mDrawable = drawable;
    }

    public void setSpacingRes(@DimenRes int spacingRes) {
        mSpacing = spacingRes;
    }

    public void setSize(@DimenRes int dimenRes) {
        mSize = dimenRes;
    }

    public void show() {
        initIndicators();
        setIndicatorAsSelected(mInitialPage);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mViewPager.setCurrentItem(1);
            }
        }, 2500);
    }

    private void initIndicators() {
        if (mContainer == null || mPageCount <= 0) {
            return;
        }

        mViewPager.addOnPageChangeListener(this);
        Resources res = mContext.getResources();
        mContainer.removeAllViews();
        for (int i = 0; i < mPageCount; i++) {
            View view = new View(mContext);
            int dimen = mSize != 0 ? res.getDimensionPixelSize(mSize) : ((int) res.getDisplayMetrics().density * defaultSizeInDp);
            int margin = mSpacing != 0 ? res.getDimensionPixelSize(mSpacing) : ((int) res.getDisplayMetrics().density * defaultSpacingInDp);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(dimen, dimen);
            lp.setMargins(i == 0 ? 0 : margin, 0, 0, 0);
            view.setLayoutParams(lp);
            view.setBackgroundResource(mDrawable);
            view.setSelected(i == 0);
            mContainer.addView(view);
        }
    }

    private void setIndicatorAsSelected(int index) {
        if (mContainer == null) {
            return;
        }
        for (int i = 0; i < mContainer.getChildCount(); i++) {
            View view = mContainer.getChildAt(i);
            view.setSelected(i == index);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        int index = position % mPageCount;
        setIndicatorAsSelected(index);
        final int moveTo = position + 1;
        try {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mViewPager.setCurrentItem(moveTo);
                }
            }, 2500);
        }catch (Exception e){
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public void cleanup() {
        mViewPager.clearOnPageChangeListeners();
    }
}

SliderPagerAdapter.java

Java:
public class SliderPagerAdapter extends FragmentStatePagerAdapter {

    private static final String TAG = "SliderPagerAdapter";

    List<Fragment> mFrags = new ArrayList<>();

    public SliderPagerAdapter(FragmentManager fm, List<Fragment> frags) {
        super(fm);
        mFrags = frags;
    }

    [USER=1021285]@override[/USER]
    public Fragment getItem(int position) {
        int index = position % mFrags.size();
        return FragmentSlider.newInstance(mFrags.get(index).getArguments().getString("params"));
    }

    [USER=1021285]@override[/USER]
    public int getCount() {
        return Integer.MAX_VALUE;
    }

}

SliderView.java

Java:
public class SliderView extends ViewPager {

    public static final int DEFAULT_SCROLL_DURATION = 250;
//    public static final int SLIDE_MODE_SCROLL_DURATION = 1000;

    public SliderView(Context context) {
        super(context);
        init();
    }

    public SliderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setDurationScroll(DEFAULT_SCROLL_DURATION);
        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
    }
    public void setDurationScroll(int millis) {
        try {
            Class<?> viewpager = ViewPager.class;
            Field scroller = viewpager.getDeclaredField("mScroller");
            scroller.setAccessible(true);
            scroller.set(this, new OwnScroller(getContext(), millis));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class OwnScroller extends Scroller {

        private int durationScrollMillis = 1;

        public OwnScroller(Context context, int durationScroll) {
            super(context, new DecelerateInterpolator());
            this.durationScrollMillis = durationScroll;
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, durationScrollMillis);
        }
    }
}
 
Last edited:
Do you have id named sliderView in activity_main.xml?
no, I put the id on fragment_home.xml ,

this fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--<RelativeLayout
android:id="@+id/layout_top"
android:layout_width="match_parent"
android:layout_height="200dp">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.yk.danaberkah._sliders.SliderView
android:id="@+id/sliderView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</FrameLayout>

<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_indicator"/>

<LinearLayout
android:id="@+id/pagesContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:layout_marginBottom="8dp"
android:gravity="center_horizontal"
android:orientation="horizontal"/>

</RelativeLayout>
 
zAjH3LG.jpg
 
Back
Top Bottom