ArrayList上的java.lang.IndexOutOfBoundsException

时间:2016-01-19 14:24:20

标签: android arraylist indexoutofboundsexception

当我从一个活动打开活动时遇到麻烦,当我按下手机的后退按钮时,应用程序崩溃了。在这里,我描述了活动和片段的所有细节。

FeedFragment.java

public class FeedFragment extends BaseFragment {

    ListView lvFeeds;
    TextView tvNoRecord;

    public static Handler[] handler;
    public static Runnable[] animateViewPager;

    static Handler bannerHandler;
    static Runnable bannerRunnable;
    boolean stopSliding = false;
    boolean isLastItemLoaded = false;
    FeedAdapter feedAdapter;
    ArrayList<FeedBean> feedList = new ArrayList<>();

    int[] bannerImages = new int[]{
            R.drawable.ic_feed_one,
            R.drawable.ic_feed_two,
            R.drawable.ic_feed_three,
            R.drawable.ic_feed_four,
            R.drawable.ic_feed_five
    };
    String articleId;
    static int position = 0;

    @SuppressLint("NewApi")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_feed, container, false);
        lvFeeds = (ListView) view.findViewById(R.id.lvFeeds);
        tvNoRecord = (TextView) view.findViewById(R.id.tvNoRecord);

        LayoutInflater mInflater = (LayoutInflater) getActivity()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        final View headerView = mInflater.inflate(R.layout.feed_banner_view, null);

        CirclePageIndicator cpiBanner = (CirclePageIndicator) headerView.findViewById(R.id.indicators);
        final JazzyViewPager vpFeedBanner = (JazzyViewPager) headerView.findViewById(R.id.vpFeeds);
vpFeedBanner.setTransitionEffect(JazzyViewPager.TransitionEffect.Accordion);
        BannerAdapter pagerAdapter = new BannerAdapter(vpFeedBanner);
        vpFeedBanner.setAdapter(pagerAdapter);
        cpiBanner.setViewPager(vpFeedBanner);

        cpiBanner.setCurrentItem(vpFeedBanner.getCurrentItem());

         lvFeeds.addHeaderView(headerView);

        listFeed();
        bannerHandler = new Handler();
        bannerRunnable = new Runnable() {
            public void run() {
                try {
                    if (position >= bannerImages.length - 1) {
                        vpFeedBanner.setCurrentItem(0);
                    } else {
                        vpFeedBanner.setCurrentItem(
                                vpFeedBanner.getCurrentItem() + 1, true);
                    }
                    bannerHandler.postDelayed(bannerRunnable, Constant.VP_ANIMATION_TIME);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            if (!feedList.isEmpty())
                setAllSlidingAnimation(feedList.size());
            bannerHandler.postDelayed(bannerRunnable, Constant.VP_ANIMATION_TIME);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            if (bannerHandler != null) {
                bannerHandler.removeCallbacks(bannerRunnable);
            }

            if (!feedList.isEmpty())
                removeAllSlidingAnimation(feedList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    class BannerAdapter extends PagerAdapter {
        JazzyViewPager vpFloor;
        LayoutInflater mInflater;

        public BannerAdapter(JazzyViewPager viewPager) {
            this.vpFloor = viewPager;
            mInflater = (LayoutInflater) getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        class ViewHolder {
            RoundedImageView ivFeed;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(vpFloor.findViewFromObject(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            final ViewHolder viewHolder = new ViewHolder();

            View layout = mInflater.inflate(R.layout.row_feed_view_pager_banner, null);
            viewHolder.ivFeed = (RoundedImageView) layout.findViewById(R.id.ivFeed);
            try {
                BaseActivity.setImageToBanner(getActivity(), bannerImages[position], viewHolder.ivFeed);

         viewHolder.ivFeed.setImageDrawable(getResources().getDrawable(bannerImages[position]));

                vpFloor.setObjectForPosition(layout, position);

                container.addView(layout);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return layout;
        }

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

        @Override
        public boolean isViewFromObject(View view, Object object) {
            if (view instanceof OutlineContainer) {
                return ((OutlineContainer) view).getChildAt(0) == object;
            } else {
                return view == object;
            }
        }
    }

 void listFeed() {
        BaseActivity.showLoader(getActivity());

        JSONObject feedObj = null;
        RequestQueue queue = Volley.newRequestQueue(getActivity());

        final String serverRequest = Constant.WEB_SERVICE_LIST_FEED;
        Log.e("", "ListFeed URL : " + serverRequest);

        JsonObjectRequest jsObjRequest = new JsonObjectRequest(
                com.android.volley.Request.Method.POST, serverRequest,
                null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Log.e("",
                            "ListFeed Response : " + response.toString());

                    JSONObject serverResponse = response
                            .getJSONObject(Constant.LIST_FEED_ACTION);

                    String Ws_Status = serverResponse.getString(Constant.TAG_STATUS);
                    String Ws_Message = serverResponse.getString(Constant.TAG_MESSAGE);

                    BaseActivity.hideLoader();

                    if (serverResponse.getString(Constant.TAG_STATUS)
                            .equalsIgnoreCase(Constant.TAG_STATUS_FAILURE)) {


                    } else {

                        feedList.clear();
                        JSONArray categoriesArray = serverResponse.getJSONArray(Constant.TAG_CATEGORIES);
                            int categoryLength = categoriesArray.length();

                        handler = new Handler[categoryLength + 1];
                        animateViewPager = new Runnable[categoryLength + 1];
                        for (int i = 0; i < categoriesArray.length(); i++) {
                         JSONObject categoriesObject = categoriesArray.getJSONObject(i);
                         FeedBean feedBean = new FeedBean();
                            feedBean.setId(categoriesObject.getString(Constant.TAG_ID));
                            feedBean.setName(categoriesObject.getString(Constant.TAG_NAME));

                            JSONArray articles = categoriesObject.getJSONArray(Constant.TAG_ARTICLES);
                            ArrayList<ArticleBean> articleList = new ArrayList<>();
                            for (int j = 0; j < articles.length(); j++) {
                                JSONObject articlesObject = articles.getJSONObject(j);

                                ArticleBean articleBean = new ArticleBean();
                                articleBean.setId(articlesObject.getString(Constant.TAG_ID));
                                articleBean.setTitle(articlesObject.getString(Constant.TAG_TITLE));
                                articleBean.setTimeLapsed(articlesObject.getString(Constant.TAG_TIME_LAPSED));
                                articleBean.setBody(articlesObject.getString(Constant.TAG_BODY));
                                articleBean.setArticleUrl(articlesObject.getString(Constant.TAG_ARTICLE_URL));
                                articleBean.setTags(articlesObject.getString(Constant.TAG_TAGS));
                                articleBean.setUserId(articlesObject.getString(Constant.TAG_USER_ID));
                                articleBean.setFeaturedImage(articlesObject.getString(Constant.TAG_FEATURED_IMAGE));
                                articleBean.setLikeCounter(articlesObject.getString(Constant.TAG_LIKE_COUNTER));
                                articleBean.setLocation(articlesObject.getString(Constant.TAG_LOCATION));
                                articleList.add(articleBean);
                            }
                             feedBean.articleBeanList = articleList;
                            int articleLength = articles.length();
                            feedBean.setArticleLength(articleLength);
                            feedList.add(feedBean);

                        }
                        feedAdapter = new FeedAdapter();
                        lvFeeds.setAdapter(feedAdapter);

                        removeAllSlidingAnimation(feedList.size());
                        setAllSlidingAnimation(feedList.size());
                    }
                } catch (Exception e) {
                    BaseActivity.hideLoader();
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError e) {
                BaseActivity.hideLoader();
                e.printStackTrace();
            }
        });

        jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(Constant.WEB_SERVICE_TIME_OUT,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(jsObjRequest);
    }

   void removeAllSlidingAnimation(int length) {
        try {
            for (int i = 0; i < length; i++) {
                if (handler[i] != null) {
                      handler[i].removeCallbacks(animateViewPager[i]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void setAllSlidingAnimation(int length) {
        try {
            for (int i = 0; i < length; i++) {
                if (handler[i] != null) {
                    handler[i].postDelayed(animateViewPager[i], Constant.VP_ANIMATION_TIME);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public void runnable(final int size, final JazzyViewPager mViewPager, final int position) {

        try {
            handler[position] = new Handler();
                animateViewPager[position] = new Runnable() {
                public void run() {
                    if (!stopSliding) {
                        if (mViewPager.getCurrentItem() == size - 1) {
                            mViewPager.setCurrentItem(0);
                        } else {
                            mViewPager.setCurrentItem(
                                    mViewPager.getCurrentItem() + 1, true);
                        }
                        try {
                            handler[position].postDelayed(animateViewPager[position], Constant.VP_ANIMATION_TIME);
                        } catch (NullPointerException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
class FeedAdapter extends BaseAdapter {

        private LayoutInflater inflater = null;

        public FeedAdapter() {
            inflater = (LayoutInflater) getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return feedList.size();
        }

        @Override
        public Object getItem(int position) {
            return feedList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup parent) {
            View itemView = convertView;
            ViewHolder viewHolder = null;

            if (convertView == null) {
                itemView = inflater.inflate(R.layout.row_feed, null);
                viewHolder = new ViewHolder();
                viewHolder.llFeed = (LinearLayout) itemView.findViewById(R.id.llFeed);
                viewHolder.vpFeeds = (JazzyViewPager) itemView.findViewById(R.id.vpFeeds);
                viewHolder.indicators = (CirclePageIndicator) itemView.findViewById(R.id.indicators);
                viewHolder.tvFeedTitle = (TextView) itemView.findViewById(R.id.tvFeedTitle);
                viewHolder.tvFeedSubTitle = (TextView) itemView.findViewById(R.id.tvFeedSubTitle);
                viewHolder.tvFeedTime = (TextView) itemView.findViewById(R.id.tvFeedTime);
                viewHolder.tvCategoryName = (TextView) itemView.findViewById(R.id.tvCategoryName);
                viewHolder.vpFeeds.setTransitionEffect(JazzyViewPager.TransitionEffect.Accordion);
                itemView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) itemView.getTag();
            }
       try {
                FeedBean bean = feedList.get(i);
                FeedPagerAdapter pagerAdapter = new FeedPagerAdapter(viewHolder.vpFeeds, viewHolder.tvFeedTitle, viewHolder.tvFeedSubTitle, viewHolder.tvFeedTime, bean, viewHolder.llFeed, viewHolder.indicators);
                viewHolder.vpFeeds.setAdapter(pagerAdapter);
                viewHolder.indicators.setViewPager(viewHolder.vpFeeds);
                viewHolder.indicators.setCurrentItem(viewHolder.vpFeeds.getCurrentItem());
                viewHolder.tvCategoryName.setText(bean.getName().toUpperCase().trim());

                if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_FEATURED)) {
                    viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_yellow));
                } else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_ORIGINAL)) {
                    viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_purple));
                } else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_MUSIC)) {
                    viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_pink));
                } else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_GIVE)) {
                    viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_lightGreen));
                } else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_LIFESTYLE)) {
                    viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_parrot));
                } else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_INSPIRATION)) {
                    viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_lightRed));
                } else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_TECH)) {
                    viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_lightBlack));
                } else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_FASHION)) {
                    viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_lightBlue));
                } else {
                    viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_pink));
                }
         runnable(bean.getArticleLength(), viewHolder.vpFeeds, i);
                if (i != 0)
                    if ((i + 1) % 2 == 0) {
                        if (!isLastItemLoaded) {
                            removeAllSlidingAnimation(i);
                            setAllSlidingAnimation(i);
                        }
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return itemView;
        }


        class ViewHolder {

            JazzyViewPager vpFeeds;
            TextView tvFeedTitle, tvFeedSubTitle, tvFeedTime, tvCategoryName;
            CirclePageIndicator indicators;
            LinearLayout llFeed;


        }
    }
        class FeedPagerAdapter extends PagerAdapter {

        JazzyViewPager vpFloor;
        private LayoutInflater mInflater;
        TextView tvFeedTitle, tvFeedSubTitle, tvFeedTime;
        FeedBean bean;
        LinearLayout llFeed;
        CirclePageIndicator indicators;

        public FeedPagerAdapter(JazzyViewPager vpFloor, TextView tvFeedTitle, TextView tvFeedSubTitle, TextView tvFeedTime, FeedBean bean, LinearLayout llFeed, CirclePageIndicator indicators) {

            this.vpFloor = vpFloor;
            mInflater = (LayoutInflater) getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            this.tvFeedTitle = tvFeedTitle;
            this.tvFeedTime = tvFeedTime;
            this.tvFeedSubTitle = tvFeedSubTitle;
            this.bean = bean;
            this.llFeed = llFeed;
            this.indicators = indicators;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(vpFloor.findViewFromObject(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            final ViewHolder viewHolder = new ViewHolder();

            View layout = mInflater.inflate(R.layout.row_feed_view_pager, null);
            viewHolder.ivFeed = (RoundedImageView) layout.findViewById(R.id.ivFeed);
            try {
                BaseActivity.setImageToView(getActivity(), bean.articleBeanList.get(position).getFeaturedImage(), viewHolder.ivFeed);
            } catch (Exception e) {
                e.printStackTrace();
            }


            llFeed.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        if (bean.articleBeanList.size() == 1) {
                            openDetailActivity(bean.articleBeanList.get(position).getId());
                        } else {
                            openDetailActivity(bean.articleBeanList.get(position).getId());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            vpFloor.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    try {
                        tvFeedTitle.setText(bean.articleBeanList.get(position).getTitle().toUpperCase());
                        tvFeedSubTitle.setText(bean.articleBeanList.get(position).getBody().toUpperCase());
                        tvFeedTime.setText(bean.articleBeanList.get(position).getTimeLapsed().toUpperCase());
                        articleId = bean.articleBeanList.get(position).getId();
                        indicators.setCurrentItem(position);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        if (bean.articleBeanList.size() == 1) {
                            openDetailActivity(bean.articleBeanList.get(position).getId());
                        } else {
                            openDetailActivity(bean.articleBeanList.get(position).getId());
                        }
                    } catch (Exception e) {
                    }
                }
            });

            try {
                vpFloor.setObjectForPosition(layout, position);
                tvFeedTitle.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getTitle().toUpperCase());
                tvFeedTitle.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getTitle().toUpperCase());
                tvFeedSubTitle.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getBody().toUpperCase());
                tvFeedTime.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getTimeLapsed().toUpperCase());
                articleId = bean.articleBeanList.get(vpFloor.getCurrentItem()).getId();
            } catch (Exception e) {
                e.printStackTrace();
            }

            container.addView(layout);

            return layout;
        }

        class ViewHolder {
            RoundedImageView ivFeed;
        }

        @Override
        public int getCount() {
            return bean.getArticleLength();
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            if (view instanceof OutlineContainer) {
                return ((OutlineContainer) view).getChildAt(0) == obj;
            } else {
                return view == obj;
            }
        }
    }

    void openDetailActivity(String articleId) {
        startActivity(new Intent(DashboardActivity.context, StoriesDetailsActivity.class).putExtra(Constant.TAG_ID, articleId));
    }
}

logcat的

FATAL EXCEPTION: main
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: Process: com.cultureapp, PID: 19925
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime:     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime:     at java.util.ArrayList.get(ArrayList.java:308)
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime:     at android.widget.HeaderViewListAdapter.isEnabled(HeaderViewListAdapter.java:164)

2 个答案:

答案 0 :(得分:1)

在你的代码中,你正在调用list.get(1),但列表大小为1.因此,你只能调用list.get(0)。您正试图触及不存在的对象。

答案 1 :(得分:0)

java.lang.IndexOutOfBoundsException表示:

你有一个ArrayList,它有1个元素,所以你只能得到位置0的元素。 但是在这里,你试图访问位置1的元素,这是不可能的,因为它不存在。

问题可能在这里:

@Override
public void onResume() {
    super.onResume();
    try {
        if (!feedList.isEmpty())
            setAllSlidingAnimation(feedList.size());
            ...
}

如果feedList的尺寸为1,您将尝试访问 SECOND 元素(第一个位于第0位,第二个位于位置1 == feedList.size() )。