ArrayIndexOutOfBoundsException на вводном экране - PullRequest
0 голосов
/ 01 июля 2018

У меня есть похожая проблема, описанная в этом посте. Там нет ответов - ошибка экрана ввода Android при добавлении на 8 экран, но не ошибка, если экран 4

Тем не менее, у меня есть 4 приветственных слайда, и приложение показывает только 2 из них. Третий просто имеет ошибку. Мой код:

public class WelcomeActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private MyViewPagerAdapter myViewPagerAdapter;
    private LinearLayout dotsLayout;
    private TextView[] dots;
    private int[] layouts;
    private Button btnSkip, btnNext;
    private PrefManager prefManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Checking for first time launch - before calling setContentView()
        prefManager = new PrefManager(this);
        if (!prefManager.isFirstTimeLaunch()) {
            launchHomeScreen();
            finish();
        }

        // Making notification bar transparent
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }

        setContentView(R.layout.activity_welcome);

        viewPager = (ViewPager) findViewById(R.id.view_pager);
        dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
        btnSkip = (Button) findViewById(R.id.btn_skip);
        btnNext = (Button) findViewById(R.id.btn_next);


        // layouts of all welcome sliders
        // add few more layouts if you want
        layouts = new int[]{
                R.layout.welcome_slide1,
                R.layout.welcome_slide2,
                R.layout.welcome_slide3,
                R.layout.welcome_slide4};

        // adding bottom dots
        addBottomDots(0);

        // making notification bar transparent
        changeStatusBarColor();

        myViewPagerAdapter = new MyViewPagerAdapter();
        viewPager.setAdapter(myViewPagerAdapter);
        viewPager.addOnPageChangeListener(viewPagerPageChangeListener);

        btnSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchHomeScreen();
            }
        });

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checking for last page
                // if last page home screen will be launched
                int current = getItem(+1);
                if (current < layouts.length) {
                    // move to next screen
                    viewPager.setCurrentItem(current);
                } else {
                    launchHomeScreen();
                }
            }
        });
    }

    private void addBottomDots(int currentPage) {
        dots = new TextView[layouts.length];

        int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
        int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);

        dotsLayout.removeAllViews();
        for (int i = 0; i < dots.length; i++) {
            dots[i] = new TextView(this);
            dots[i].setText(Html.fromHtml("&#8226;"));
            dots[i].setTextSize(35);
            dots[i].setTextColor(colorsInactive[currentPage]);
            dotsLayout.addView(dots[i]);
        }

        if (dots.length > 0)
            dots[currentPage].setTextColor(colorsActive[currentPage]);
    }

    private int getItem(int i) {
        return viewPager.getCurrentItem() + i;
    }

    private void launchHomeScreen() {
        prefManager.setFirstTimeLaunch(false);
        startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
        finish();
    }

    //  viewpager change listener
    ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            addBottomDots(position);

            // changing the next button text 'NEXT' / 'GOT IT'
            if (position == layouts.length - 1) {
                // last page. make button text to GOT IT
                btnNext.setText(getString(R.string.start));
                btnSkip.setVisibility(View.GONE);
            } else {
                // still pages are left
                btnNext.setText(getString(R.string.next));
                btnSkip.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }
    };

    /**
     * Making notification bar transparent
     */
    private void changeStatusBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    /**
     * View pager adapter
     */
    public class MyViewPagerAdapter extends PagerAdapter {
        private LayoutInflater layoutInflater;

        public MyViewPagerAdapter() {
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View view = layoutInflater.inflate(layouts[position], container, false);
            container.addView(view);

            return view;
        }

        @Override
        public int getCount() {
            return layouts.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == obj;
        }


        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            View view = (View) object;
            container.removeView(view);
        }
    }
}

Ошибка:

07-01 11:17:24.961 10911-10911/com.google.android.gms.samples.vision.ocrreader E/InputEventReceiver: Exception dispatching input event.
07-01 11:17:24.961 10911-10911/com.google.android.gms.samples.vision.ocrreader E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
07-01 11:17:24.967 10911-10911/com.google.android.gms.samples.vision.ocrreader E/MessageQueue-JNI: java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
        at com.google.android.gms.samples.vision.ocrreader.WelcomeActivity.addBottomDots(WelcomeActivity.java:107)
        at com.google.android.gms.samples.vision.ocrreader.WelcomeActivity.access$300(WelcomeActivity.java:21)
        at com.google.android.gms.samples.vision.ocrreader.WelcomeActivity$3.onPageSelected(WelcomeActivity.java:130)
        at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1941)
        at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:680)
        at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:664)
        at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2257)
        at android.view.View.dispatchTouchEvent(View.java:9314)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2592)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2283)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2598)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2297)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2598)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2297)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2598)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2297)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2598)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2297)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2598)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2297)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2598)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2297)
        at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2430)
        at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent_aroundBody0(PhoneWindow.java:1762)
        at com.android.internal.policy.PhoneWindow$AjcClosure1.run(PhoneWindow.java:1)
        at android.view.PhoneWindowAO.ajc$around$android_view_PhoneWindowAO$4$99ce526bproceed(PhoneWindowAO.aj:149)
        at android.view.PhoneWindowAO.ajc$around$android_view_PhoneWindowAO$4$99ce526b(PhoneWindowAO.aj:153)
        at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1762)
        at android.app.Activity.dispatchTouchEvent(Activity.java:2807)
        at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
        at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2391)
        at android.view.View.dispatchPointerEvent(View.java:9534)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4422)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4288)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3739)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3792)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3758)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3766)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3739)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3792)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3758)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3885)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3766)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3942)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3739)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3792)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3758)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3766)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3739)
        at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6146)
        at android.view

1 Ответ

0 голосов
/ 01 июля 2018

Относительно вашей проблемы на

dots[i].setTextColor(colorsInactive[currentPage]);

вы получаете colorsInactive из ресурсов

int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);

Вы найдете их в src / main / res / arrays.xml или в файле с аналогичным именем. Определенные там массивы имеют имена array_dot_[in]active и содержат только два элемента. Чтобы ваш код работал, вам нужно добавить еще два цвета в эти массивы или изменить сам код, чтобы отразить тот факт, что есть только два цвета.

Один из способов сделать это - использовать %2 или &1, которые дают одинаковое значение ( 0, если четное, 1, если нечетное ):

dots[i].setTextColor(colorsInactive[currentPage & 1]);
...