Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove item from recyclerView in android

In my application I should use recyclerView and remove some items.
I want remove some items from recyclerview and for this I write below code in Adapter :

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private Context context;
    private List<TvTonightResult> model;

    public MyAdapter (Context context, List<TvTonightResult> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_tv_tonight, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, final int position) {

        holder.tvTonightTitle.setText(Html.fromHtml(model.get(position).getName()));
        Glide.with(context)
                .load(model.get(position).getImageUrl())
                .placeholder(R.drawable.default_image)
                .override(600, 900)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.tvTonightImage);

        long time = 5 * 1000;
        holder.tvTonightTimeCounter.start(time);
        holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                removeItem(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return 4;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView tvTonightImage, tvTonightChannel;
        private TextView tvTonightTitle, tvTonightDate;
        private CountdownView tvTonightTimeCounter;

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

            tvTonightImage = (ImageView) itemView.findViewById(R.id.row_tvTonightImage);
            tvTonightChannel = (ImageView) itemView.findViewById(R.id.row_tvTonightChannelImage);
            tvTonightTitle = (TextView) itemView.findViewById(R.id.row_tvTonightTitle);
            tvTonightTimeCounter = (CountdownView) itemView.findViewById(R.id.row_tvTonightTime);

        }
    }

    private void removeItem(int position) {
        model.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, model.size());
    }
}

I want when run this code, remove item :

holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
                @Override
                public void onEnd(CountdownView cv) {
                    removeItem(position);
                }
            });

But show me this error :

FATAL EXCEPTION: main
Process: com.example.app, PID: 9711
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.remove(ArrayList.java:477)
    at com.example.app.Adapters.TvTonightAdapter.removeItem(TvTonightAdapter.java:102)
    at com.example.app.Adapters.TvTonightAdapter.access$300(MyAdapter.java:29)
    at com.example.app.Adapters.TvTonightAdapter$2.onEnd(MyAdapter.java:74)
    at com.example.app.Utils.Componenets.CountDownTimer.CountdownView$1.onFinish(CountdownView.java:129)
    at com.example.app.Utils.Componenets.CountDownTimer.CustomCountDownTimer$1.handleMessage(CustomCountDownTimer.java:74)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6247)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

How can I fix this error and remove item from recyclerview?

like image 451
Kol Avatar asked Jun 05 '17 14:06

Kol


People also ask

How to display recycler items in Android app?

Go to the app > java > Right-Click on your app’s package name > New > Java Class and name the file as RecyclerData. This class will handles data for each Recycler item that is to be displayed.

How to delete an item from recyclerview?

The idea of deleting an item from recyclerview is that we need to delete it from the datasource and call an API to delete it from the server. For this example, we will not use one API call because I don’t have a server where you can delete item :). We will delete the item locally i.e. from the recyclerview.

How to create a recyclerview layout in Android app?

Go to the app > res > layout> right-click > New > Layout Resource File and name the file as card_layout. In this file, all XML code related to card items in the RecyclerView is written. Below is the code for the card_layout.xml file. Go to the app > java > Right-Click on your app’s package name > New > Java Class and name the file as RecyclerData.

How to add delete button to recycler view item layout?

Let’s add one delete button to the recycler view item layout list_item.xml. It looks as like below : The code for this xml file is as below: Inside the adapter class, we will get the reference of the delete button and on click of this button, we will call one function that deletes the data:


3 Answers

just try ,

int actualPosition = holder.getAdapterPosition();

in your removeItem() method and replace position with actualPosition.

like ,

  private void removeItem(int position) {
    int actualPosition = holder.getAdapterPosition();
    model.remove(actualPosition);
    notifyItemRemoved(actualPosition);
    notifyItemRangeChanged(actualPosition, model.size());
}
like image 91
Omkar Avatar answered Oct 17 '22 22:10

Omkar


I think you should call remove(holder.getAdapterPosition()) instead of remove(position) because, when the holder's countdown finishes, it might have changed its position.

Suppose the following situation:

1º holder -> 5 seconds countdown

2º holder -> 10 seconds countdown

Since the second holder finishes after the first one, after 10 seconds, remove(1) will be called but, since the first holder has already been removed, the second holder's position will be 0. Hence, it should call remove(0) instead of remove(1) (which will cause an IndexOutOfBoundsException).

like image 41
Gabriel Costa Avatar answered Oct 17 '22 23:10

Gabriel Costa


Remove the item in Arraylist in Android

holder.mRemoveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Get the clicked item label
                String itemLabel = mDataSet.get(position);
                // Remove the item on remove/button click
                mDataSet.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position,mDataSet.size());
                // Show the removed item label`enter code here`
                Toast.makeText(mContext,"Removed : " + itemLabel,Toast.LENGTH_SHORT).show();

}
like image 2
Sanjay Umaraniya Avatar answered Oct 17 '22 23:10

Sanjay Umaraniya