简体   繁体   中英

Removing view of recycler view

In my application, i am using a recycler view and a array list as its datasource for the adapter, the problem is after i remove the index from the array list, i don't know how to remove view at that index from recyclerview which results in application crashing sometimes.

Here is the fragment where i am defining and initializing the recycler view .

public class PastClasses extends Fragment{
ArrayList<GetAllPastClasses> Pastclasslist;
View rootView;
Context mcontext;

RecyclerView rv;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.activity_main, container, false);

        Bundle bn = getArguments();

        Pastclasslist = (ArrayList<GetAllPastClasses>) bn.getSerializable("class_detailss");


        mcontext = PastClasses.this.getActivity();
        rv = (RecyclerView) rootView.findViewById(R.id.rv);

        LinearLayoutManager llm = new LinearLayoutManager(mcontext);
        rv.setLayoutManager(llm);
        rv.setHasFixedSize(true);


        PastClassesAdapter adapter = new PastClassesAdapter(Pastclasslist, mcontext);

        //final Class_Details_PagerAdapter adapter = new Class_Details_PagerAdapter(getSupportFragmentManager(), 2);
        rv.setAdapter(adapter);

    return rootView;
}

And here is the Adapter class. Here in the remove method i am removing the item from list but i don't know how to remove view from the recycler view .

    public class PastClassesAdapter extends RecyclerView.Adapter<PastClassesAdapter.PersonViewHolder> {

private static final String TAG = "CustomAdapter";
String STARTPOINT = "https://www.vario.fitness";
ArrayList<GetAllPastClasses> Pastclasslist;
CancelClass cnclass;
String user_id ="442";
public static class PersonViewHolder extends RecyclerView.ViewHolder {
    CardView cv;
    TextView txt_class_name; //txt_class_name
    TextView txt_bsns_name;
    ImageView img_class;
    ImageView img_rate;
    ImageView img_timer;
    TextView txt_area_name;
    TextView txt_time;

    public PersonViewHolder(View itemView) {
        super(itemView);
        // Define click listener for the ViewHolder's View.


        cv = (CardView) itemView.findViewById(R.id.cvPastClasses);
        txt_class_name = (TextView) itemView.findViewById(R.id.txt_class_name);
        txt_bsns_name = (TextView) itemView.findViewById(R.id.txt_bsns_name);
        img_timer = (ImageView) itemView.findViewById(R.id.img_timer);
        txt_area_name = (TextView) itemView.findViewById(R.id.txt_area_name);
        txt_time = (TextView)itemView.findViewById(R.id.txt_time);
        img_class= (ImageView) itemView.findViewById(R.id.img_class);
        img_rate= (ImageView) itemView.findViewById(R.id.img_rate);
    }

}
Context mcontext;

public PastClassesAdapter (ArrayList<GetAllPastClasses> Pastclasslist , Context mcontext) {
    this.mcontext=mcontext;
    this.Pastclasslist = Pastclasslist;

    //System.out.println("size:  "+Pastclasslist.size());
}

public int getItemCount() {
    return Pastclasslist.size();
}

public void remove(GetAllPastClasses item) {
    int position = Pastclasslist.indexOf(item);
    Pastclasslist.remove(position);
    notifyItemRemoved(position);
}


public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.content_main_pastclass, viewGroup, false);
    PersonViewHolder pvh = new PersonViewHolder(v);
    return pvh;
}
// String name, String date, int photoId, String rate, String review

public void onBindViewHolder(final PersonViewHolder personViewHolder, final int i) {

        if (!checkNullity(Pastclasslist.get(i).getClassName())) {

                  personViewHolder.txt_class_name.setText(Pastclasslist.get(i).getClassName());

        } else {
            personViewHolder.txt_class_name.setText("GYM CLASS");
        }
        if (!checkNullity(Pastclasslist.get(i).getArea())) {
            personViewHolder.txt_area_name.setText(Pastclasslist.get(i).getArea());
        }
        if (!checkNullity(Pastclasslist.get(i).getBusinessName())) {
            personViewHolder.txt_bsns_name.setText(Pastclasslist.get(i).getBusinessName());
        }
        if (!checkNullity(Pastclasslist.get(i).getClassDuration()) && !checkNullity(Pastclasslist.get(i).getSchdDate())) {
            personViewHolder.txt_time.setText(Pastclasslist.get(i).getSchdDate().substring(11, 16) + " | " + Pastclasslist.get(i).getClassDuration());
        }
        if (!checkNullity(Pastclasslist.get(i).getPhoto())) {
            //   personViewHolder.Userprofilepic.setImageResource((persons[i].getPhoto()));

            Picasso.with(mcontext).load(Pastclasslist.get(i).getPhoto().replace("\\", "").replaceAll(" ", "%20"))
                    .error(R.mipmap.ic_launcher).into(personViewHolder.img_class);
        } else if (checkNullity(Pastclasslist.get(i).getPhoto())) {
            personViewHolder.img_class.setImageResource(R.mipmap.ic_launcher);

        }

        personViewHolder.img_rate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mcontext);
                alertDialogBuilder.setTitle("Cancel Class");
                alertDialogBuilder.setMessage("Are you sure,You want to cancel this class");
                alertDialogBuilder.setIcon(R.mipmap.ic_launcher);
                alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        //Toast.makeText(mcontext, "You clicked yes button", Toast.LENGTH_LONG).show();
                        MainActivity.pLoading.setMessage("Cancelling..");
                        MainActivity.pLoading.show();

                        // POJO class GetAllPastClasses
                        final OkHttpClient client = new OkHttpClient();
                        final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                        client.interceptors().add(interceptor);

                        Retrofit retrofit = new Retrofit.Builder().baseUrl(STARTPOINT).addConverterFactory(GsonConverterFactory.create())
                                .client(client).build();
                        RestInterface restInterface = retrofit.create(RestInterface.class);
                        System.out.println("i is :  " + i);
                        Call<CancelClass> objInbox = restInterface.cancelThisClass(null, null, null, null, null);
                        try {
                            objInbox = restInterface.cancelThisClass(Pastclasslist.get(i).getResIdPk(),
                                    Pastclasslist.get(i).getClassIdFk(), Pastclasslist.get(i).getSchdIdFk(), Pastclasslist.get(i).getWeekNoSch(),
                                    user_id);

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }



                        objInbox.enqueue(new Callback<CancelClass>() {
                            @Override
                            public void onResponse(Response<CancelClass> response, Retrofit retrofit) {

                                cnclass = response.body();

                                if (cnclass.getSucc().equals("1")) {
                                    Toast.makeText(mcontext, cnclass.getMsg(), Toast.LENGTH_LONG).show();
                                    // Pastclasslist.get(i).setCanStatus("1");

                                  remove(Pastclasslist.get(i));

                                } else {
                                    Toast.makeText(mcontext, cnclass.getMsg(), Toast.LENGTH_LONG).show();
                                }
                                MainActivity.pLoading.dismiss();
                            }

                            @Override
                            public void onFailure(Throwable t) {
                                Toast.makeText(mcontext, cnclass.getMsg(), Toast.LENGTH_LONG).show();
                            }
                        });

                    }
                });

                alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });

                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        });

    }

public boolean checkNullity(String responseString) {
    if (responseString == null || responseString.equals("") ||   responseString.equals("-1")) {
        return true;
    } else {
        return false;
    }
}

public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}


}

当您从用于初始化适配器的arrayList对象中删除该项目时,只需调用:

adapter.notifyDataSetChanged();

I got the answer, I just need to use both the method notifyItemChanged and notifyItemRangeChanged so that the adapter can know that a view is deleted.Now its working fine when I changed my remove method to something below.

public void remove(GetAllPastClasses item) {
    int position = Pastclasslist.indexOf(item);
    Pastclasslist.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position,Pastclasslist.size());
}

Modify your getItemCount() and remove() method as follows :

public int getItemCount() {
        return (null != Pastclasslist ? Pastclasslist.size() : 0);
    }

remove() method

public void remove(GetAllPastClasses item) {
  int position = Pastclasslist.indexOf(item);
  if(position!=-1 && position<Pastclasslist.size())
    {
      Pastclasslist.remove(position);
      notifyItemRemoved(position);
      notifyItemRangeChanged(position, getItemCount());
    }
}

notifyItemRangeChanged(position, getItemCount()); - notifies the RecyclerView Adapter that positions of element in adapter has been changed from position(removed element index to end of list), please update it.

if(position!=-1 && position<Pastclasslist.size()) - this condition verifies that position of element is not equal to -1 and position of element should be less than size of total elements in list. hence not causing unwanted crash due to indexes of elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM