0

i am very new to Android Studio and making app with my WordPress website and using Rest Api to fetch data from my website , all works fine and i have added sort posts menu in my app and users can sort posts by "most views" "most commented" etc. and it also works fine but the problem occurred when i load all posts in app , like i have 12 posts in my website and when i go to end in app and then i click on button sort by "most views" or "most commented" then i see this error ..

 java.lang.ArrayIndexOutOfBoundsException: length=22; index=-1
        at java.util.ArrayList.remove(ArrayList.java:506)
        at com.testtest.test.PostAdapter.showHideProgress(PostAdapter.java:158)
        at com.testtest.test.MainActivity$7.onResponse(MainActivity.java:293)

this is PostAdapter

 private List<Model> dataset;
    private Context mContext;
    int total_types;
    int viewTypeData = 0,viewTypeProgress = 2 ;
    private static final int AD = 1;
    private static final int LIST_AD_DELTA = 4;

    AdView adview;



    public PostAdapter(List<Model> list){
        dataset = list;
    }

    @NotNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        if (viewType == AD) {

            adview = new AdView(mContext);
            adview.setAdSize( AdSize.LARGE_BANNER);

            adview.setAdUnitId(mContext.getResources().getString(R.string.banner_ad_unit_id));

            float density = mContext.getResources().getDisplayMetrics().density;
            int height = Math.round(AdSize.LARGE_BANNER.getHeight() * density);
            AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT, height);
            adview.setLayoutParams(params);

            new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("C5468C2B8941779E34B14EB796B9EA1B"));

            AdRequest request = new AdRequest.Builder().build();
            adview.loadAd(request);
            return new Holder(adview);


        }
        if (viewType == viewTypeData){
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_list,parent,false);
            return new MyDataHolder(view);
        }else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading,parent,false);
            return new MyProgressHolder(view);
        }
    }

    public void clearApplications() {
        int size = this.dataset.size();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                dataset.remove(0);
            }

            this.notifyItemRangeRemoved(0, size);
        }
    }





    @Override
    public void onBindViewHolder(@NotNull RecyclerView.ViewHolder holder, int position) {
        Model model = dataset.get(getRealPosition(position));

        String tagID = model.tagsid;

        if (holder instanceof MyDataHolder){
            ((MyDataHolder)holder).showModel(model);

            Glide.with(mContext)
                    .load(model.imageUrl)
                    .dontAnimate()
                    .placeholder(R.drawable.icon)
                    .into( ((MyDataHolder)holder).imageView);



        }

    }

    private int getRealPosition(int position) {
        if (LIST_AD_DELTA == 0) {
            return position;
        } else {
            return position - position / LIST_AD_DELTA;
        }
    }

    @Override
    public int getItemCount() {
        return dataset.size();
    }

    @Override
    public int getItemViewType(int position){
        if (position > 0 && position % LIST_AD_DELTA == 0) {
            return AD;
        }
        return viewTypeData;
    }
    void showHideProgress(boolean shouldShowProgress){
        if (shouldShowProgress){
            dataset.add(new Model("progress","","","","","","","","","",""));
            Handler handler = new Handler();

            final Runnable r = new Runnable() {
                public void run() {
            notifyItemInserted(dataset.size()-1);
                }
            };

            handler.post(r);

        }else {
            dataset.remove(dataset.size()-1);
            notifyItemRemoved(dataset.size()-1);
        }
    }
    void addItemsToList(List<Model> newItems){
        if (dataset.isEmpty()){
            dataset.addAll(newItems);
            notifyDataSetChanged();
        }else {
            int lastItemPosition = dataset.size() -1;
            dataset.addAll(newItems);
            notifyItemRangeInserted(lastItemPosition,newItems.size());
        }
    }
    class MyDataHolder extends RecyclerView.ViewHolder{
        TextView titleView,subTitleView,postViews,tagsView,date;
        ImageView imageView;
        ImageButton sharebtn;
        CardView rootView;
        // Use Glide to load image to image view




        public MyDataHolder(@NotNull View itemView) {
            super(itemView);
            titleView = itemView.findViewById(R.id.title);
            date = itemView.findViewById(R.id.date);
            subTitleView = itemView.findViewById(R.id.subtitle);
            postViews = itemView.findViewById(R.id.postview);
            tagsView = itemView.findViewById(R.id.tags);
            imageView = itemView.findViewById(R.id.Icon);
            sharebtn = itemView.findViewById(R.id.share);
            rootView = itemView.findViewById(R.id.recycler_item_root_view);

            tagsView.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putParcelable("my_key",dataset.get(getRealPosition(getAdapterPosition())));
                Model model = bundle.getParcelable("my_key");
                if (model != null) {
                    String tagsID = model.tagsid;
                    tagsID = tagsID.replace("[", "");
                    tagsID = tagsID.replace("]", "");
                    String newTags = null;
                    if(tagsID.contains(".")){
                        newTags = tagsID.substring(0, tagsID.indexOf("."));
                    } else {
                        newTags = tagsID;
                    }
                    String tagsName = model.tags;
                    tagsID = tagsID.replace("[", "");
                    tagsID = tagsID.replace("]", "");
                    Intent webviewIntent = new Intent(mContext, TagsActivity.class);
                    webviewIntent.putExtra("TagsID", newTags);
                    webviewIntent.putExtra("TagsName", tagsName);
                    webviewIntent.putExtra("Toolbar", "Notification");
                    mContext.startActivity(webviewIntent);
                }


            });

            sharebtn.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putParcelable("my_key",dataset.get(getRealPosition(getAdapterPosition())));
                Model model = bundle.getParcelable("my_key");
                if (model != null) {

                    String content = String.valueOf((Html.fromHtml(model.content)));

                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT,
                            model.title + "\n" + content + "\n" +
                                    mContext.getResources().getString(R.string.shareapp) + " " +
                                    mContext.getResources().getString(R.string.shareurl));
                    sendIntent.setType("text/plain");
                    mContext.startActivity(sendIntent);
                }


            });

            rootView.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putParcelable("my_key",dataset.get(getRealPosition(getAdapterPosition())));
                Intent intent = new Intent(mContext, PostDetails.class);
                intent.putExtra("my_bundle",bundle);
                mContext.startActivity(intent);
            });
        }
        void showModel(Model model){
            titleView.setText(model.title);
            tagsView.setText(model.tags);
            date.setText(model.date);
            subTitleView.setText(model.subTitle);
            postViews.setText(model.commentcount);
        }
    }
    static class MyProgressHolder extends RecyclerView.ViewHolder{
        ProgressBar progressBar;
        public MyProgressHolder(@NotNull View itemView) {
            super(itemView);
            progressBar = itemView.findViewById(R.id.progressbar);
        }
        void show(){
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    public class Holder extends RecyclerView.ViewHolder {
        public ProgressBar progressBar;

        public Holder(View itemView) {
            super(itemView);


        }
    }
}

and this is how i fetch most viewed posts

 if (id == R.id.action_view) {

            adapter.clearApplications();
            yourURL = baseURL + mostView;
            getRetrofit();
            tv.setVisibility(View.VISIBLE);
            return true;
        }

i have tried this

public void clearApplications() {
        int size = this.dataset.size() -1;
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                dataset.remove(0);
            }

            this.notifyItemRangeRemoved(0, size);
        }
    }

but it did not work properly ,, please help

6
  • 2
    According to exception message line dataset.remove(dataset.size()-1); cause this exception. Commented Jan 19, 2023 at 17:17
  • I agree with @Rasul. You should make sure that either dataset has at least one entry or check to see if it is empty and act accordingly. Maybe dataset should never be empty? Commented Jan 19, 2023 at 17:20
  • @Rasul yes thats what causing the issue , but how can i resolve that ? Commented Jan 19, 2023 at 17:32
  • Not completely explained thus far; the 22 in the exception messsage comes directly from the size and your code does size()-1 - is this a multithreaded application? Commented Jan 19, 2023 at 17:37
  • @noorapps Could you please share whole class? Commented Jan 19, 2023 at 17:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.