0

i have a created an android app with a recyclerview. each row in the recyclerview has 3 textviews and an edittext. the data is added to the recyclerview from a dialogfragment list that i created. i liked to implement a delete when swiped method to my recyclerview and it worked, but not perfectly. the thing is that when i first add items from the list and then swipe to delete, the swiping works and the recyclerview is updated. but when i add items to the recyclerview, then open my list and add new items to my recyclerview, the swiping doesn't work properly. i tried to understand what the problem is but i couldn't figure it out. i made a work around solution but i'm not satisfied with it. i'll show you my codes:

this is my dialog fragment for the list

 public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View view = inflater.Inflate(Resource.Layout.list, container, false);
            lst = view.FindViewById<ListView>(Resource.Id.list_options);
            check = view.FindViewById<CheckBox>(Resource.Id.checkBox1);
            title = view.FindViewById<TextView>(Resource.Id.spinnerTitle);
            ok = view.FindViewById<Button>(Resource.Id.ok);
          
            check.CheckedChange += delegate
            {
                if (check.Checked == true)
                {
                    adp = new list_adapter(this, getmodel(true), check);
                    lst.Adapter = adp;
                }
                else
                {
                    adp = new list_adapter(this, getmodel(false), check);
                    lst.Adapter = adp;
                }

            };

        

            WSEng.WebService5 ws = new WSEng.WebService5();
            ws.get_itemsAsync(1);
            ws.get_itemsCompleted += Ws_get_itemsCompleted;


            SearchView searchView1 = view.FindViewById<SearchView>(Resource.Id.searchView1);
            searchView1.QueryTextChange += (s, e) =>
            {

                adp.Filter.InvokeFilter(e.NewText);

            };

            searchView1.QueryTextSubmit += (s, e) =>
            {
                // Handle enter/search button on keyboard here
                Toast.MakeText(this.Context, "Searched for: " + e.Query, ToastLength.Short).Show();
                e.Handled = true;
            };

            ok.Click += delegate
            {
                selectedItems.Clear();
                selectedItems = adp.GetSelectedItems();

                sendResult(0);
                this.Dismiss();
            };

            return view;
        }

        public List<list_item> getmodel(bool selection)
        {
            List<list_item> after_selection = new List<list_item>();
            for (int i=0;i<user.tableItems.Count;i++)
            {
                user.tableItems[i].IsSelected = selection;
                after_selection.Add(user.tableItems[i]);
            }
            return after_selection;
        }
        private void Ws_get_itemsCompleted(object sender, WSEng.get_itemsCompletedEventArgs e)
        {
            try
            {
                DataTable laborers = new DataTable();
                laborers = e.Result;
                user.tableItems.Clear();
                int i = 0;

                
                foreach (DataRow row in laborers.Rows)
                {
                    user.tableItems.Add(new list_item { id = i, name = row["ItemName"].ToString(), item_code = row["itemcode"].ToString(), unit = row["itemsunitcode"].ToString(), quantity = "1", itembarcode = row["itembarcode"].ToString(), categorycode = row["itemscategorycode"].ToString(), currentQty = row["currentQuantity"].ToString(), reference = row["reference"].ToString(), model = row["model"].ToString(), categoryname = row["categoryname"].ToString(), size = row["size"].ToString(), IsSelected = false });
                    i++;

                }

                
                adp = new list_adapter(this, user.tableItems, check);
                lst.Adapter = adp;
           
            }
            catch (System.Reflection.TargetInvocationException exp)
            {
                System.Net.WebException exception = new System.Net.WebException("can't reach server", exp.InnerException);


                Toast.MakeText(this.Context, exp.InnerException.Message, ToastLength.Long).Show();


                Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this.Context);

                alert.SetTitle("Connection failed");

                alert.SetMessage("Please, Check your Internet Connection!");
                alert.SetPositiveButton("Retry", (senderAlert, args) =>
                {
                    WSEng.WebService5 ws = new WSEng.WebService5();
                    ws.get_itemsAsync(1);
                    ws.get_itemsCompleted += Ws_get_itemsCompleted;

                    alert.Dispose();
                });

                _dialog = alert.Create();

                _dialog.Show();
            }
        }

        private void sendResult(int reqcode)
        {
            Intent intent = new Intent();
            intent.PutExtra("result", JsonConvert.SerializeObject(selectedItems));
            TargetFragment.OnActivityResult(TargetRequestCode, 0, intent);
        }
        private class SearchViewExpandListener : Java.Lang.Object, MenuItemCompat.IOnActionExpandListener
        {
            private readonly IFilterable _adapter;

            public SearchViewExpandListener(IFilterable adapter)
            {
                _adapter = adapter;
            }

            public bool OnMenuItemActionCollapse(IMenuItem item)
            {
                _adapter.Filter.InvokeFilter("");
                return true;
            }

            public bool OnMenuItemActionExpand(IMenuItem item)
            {
                return true;
            }
        }


    }
}

this is the code of the fragment where my recyclerview is found. it is where i get the result of the selected items from the list fragment and fill them in the recyclerview

public override void OnActivityResult(int requestCode, int resultCode, Intent data)
        {
           
            if (requestCode == 0)
            {
                selected_data.AddRange( JsonConvert.DeserializeObject<List<list_item>>(data.GetStringExtra("result")));
              
                laborers_dt.Clear();
                int count_repeated = 0;



                for (int i = 0; i < selected_data.Count; i++)
                {
                    laborers_dt.Rows.Add(i + 1, selected_data[i].itembarcode, selected_data[i].item_code, selected_data[i].name, selected_data[i].unit, selected_data[i].quantity, selected_data[i].categorycode,"");
                }


                for (int i = 0; i < laborers_dt.Rows.Count; i++)
                {
                    count_repeated = 0;

                    for (int j = 0; j < laborers_dt_total.Rows.Count; j++)
                    {
                        if (laborers_dt.Rows[i]["itemcode"].ToString() == laborers_dt_total.Rows[j]["itemcode"].ToString())
                        {
                            count_repeated = count_repeated + 1;
                        }

                    }
                    if (count_repeated == 0)
                    {
                        laborers_dt_total.Rows.Add(laborers_dt_total.Rows.Count + 1, laborers_dt.Rows[i]["itembarcode"].ToString(), laborers_dt.Rows[i]["itemcode"].ToString(), laborers_dt.Rows[i]["name"].ToString(), laborers_dt.Rows[i]["itemsunitcode"].ToString(),
                            Convert.ToDecimal(laborers_dt.Rows[i]["itemQty"].ToString()), laborers_dt.Rows[i]["itemscategorycode"].ToString(),"");

                    }
                }

                mLayoutManager = new LinearLayoutManager(this.Context);
                mRecyclerView.HasFixedSize = true;
                mRecyclerView.SetLayoutManager(mLayoutManager);
                RecyclerviewAdapter = new recyclerviewAdapter(this, laborers_dt_total,selected_data);
                mRecyclerView.SetAdapter(RecyclerviewAdapter);
                var swipeHandler = new SwipeToDeleteCallback(0, ItemTouchHelper.Left, this.Context, RecyclerviewAdapter, laborers_dt_total,mRecyclerView);
                var itemTouchHelper = new ItemTouchHelper(swipeHandler);
                itemTouchHelper.AttachToRecyclerView(mRecyclerView);
                
            }
        }
        public class recyclerview_viewholder : RecyclerView.ViewHolder
        {
            public TextView rownbr, itemname;
            public EditText qty;
            public TextView unit;
            public LinearLayout linearLayout;
           
            public recyclerview_viewholder(View itemView, Action<int> listener)
              : base(itemView)
            {
                rownbr = itemView.FindViewById<TextView>(Resource.Id.rownbr);
                itemname = itemView.FindViewById<TextView>(Resource.Id.laborname);
                unit = itemView.FindViewById<TextView>(Resource.Id.days);
                qty = itemView.FindViewById<EditText>(Resource.Id.overtime);
                linearLayout = itemView.FindViewById<LinearLayout>(Resource.Id.linearLayout);
               
                itemView.Click += (sender, e) => listener(base.LayoutPosition);
               
            }
        }

        public class recyclerviewAdapter : RecyclerView.Adapter
        {
            // Event handler for item clicks:
            public event EventHandler<int> ItemClick;

            DataTable summary_Requests = new DataTable();
            //Context context;
            public readonly new_request_items context;
            int selected_pos = -1;
            private SwipeToDeleteCallback swipeToDeleteCallback;
            List<list_item> item_details = new List<list_item>();
            public recyclerviewAdapter(new_request_items context, DataTable sum_req, List<list_item> item_details)
            {
                this.context = context;
                summary_Requests = sum_req;
                this.item_details = item_details;

            }
            public recyclerviewAdapter(DataTable sum_req, SwipeToDeleteCallback swipeToDeleteCallback)
            {
                this.swipeToDeleteCallback = swipeToDeleteCallback;
                summary_Requests = sum_req;

            }
            public override RecyclerView.ViewHolder
                   OnCreateViewHolder(ViewGroup parent, int viewType)
            {
                View itemView = LayoutInflater.From(parent.Context).
                            Inflate(Resource.Layout.recycler_view_request_new_data, parent, false);


                recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
                user.zero_val = new string[summary_Requests.Rows.Count];
                vh.qty.TextChanged += (sender, e) =>
                {
                
                   
                    if (vh.qty.Text != "")

                        try
                        {
                           
                            int position = vh.LayoutPosition;
                            summary_Requests.Rows[position]["itemQty"] = Convert.ToDecimal(vh.qty.Text);
                            user.zero_val[position]="Not_exist";
                           
                        }
                        catch (System.FormatException exp)
                        {
                           
                            int position = vh.LayoutPosition;
                            var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
                            icon.SetBounds(0, 0, 50, 50);
                            vh.qty.SetError("qty can be decimal", icon);
                            user.zero_val[position]="exits";
                        }
                    else if (vh.qty.Text == "")
                    {
                        int position = vh.LayoutPosition;
                        var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
                        icon.SetBounds(0, 0, 50, 50);
                        vh.qty.SetError("value can not be empty", icon);
                        user.zero_val[position]="exits";
                    }

                };
                vh.ItemView.LongClick += (sender, e) =>
                {
                    int position = vh.AdapterPosition;
                    string itemcode = summary_Requests.Rows[position]["itemcode"].ToString();


                    list_item result = item_details.Find(list_item => list_item.item_code == itemcode);
                    Bundle bundle = new Bundle();
                    bundle.PutString("result", JsonConvert.SerializeObject(result));
                    items_info iteminf = new items_info();
                    iteminf.Arguments = bundle;
                    iteminf.Cancelable = true;
                    var SupportFragmentManager = this.context.FragmentManager;
                    iteminf.Show(SupportFragmentManager, "dialog");
               
                    selected_pos = position;
                    NotifyDataSetChanged();
                  };

                return vh;
            }
            public override void
                  OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
            {
                recyclerview_viewholder vh = holder as recyclerview_viewholder;

              
                vh.rownbr.Text = summary_Requests.Rows[position]["rowNumber"].ToString();
                vh.itemname.Text = summary_Requests.Rows[position]["name"].ToString();
                vh.unit.Text = summary_Requests.Rows[position]["itemsunitcode"].ToString();
                vh.qty.Text= summary_Requests.Rows[position]["itemQty"].ToString();
                if (selected_pos == position)
                    vh.ItemView.SetBackgroundColor(Color.ParseColor("#4fa5d5"));
                else
                    vh.ItemView.SetBackgroundColor(Color.LightGray);

               
            }

            public void RemoveItem(int position)
            {
                
                if (laborers_dt_total.Rows.Count != 0)
                {
                    if (position < laborers_dt_total.Rows.Count && position > -1)
                    {
                        laborers_dt_total.Rows.RemoveAt(position);
                     
                    }
                    else
                    {
                        Toast.MakeText(context.Context, "select an item to delete", ToastLength.Long).Show();

                    }

                }
                else if (laborers_dt_total.Rows.Count == 0)
                {
                    Toast.MakeText(context.Context, "no items to delete", ToastLength.Long).Show();

                }


                for (int i = 0; i < laborers_dt_total.Rows.Count; i++)
                {
                    laborers_dt_total.Rows[i]["rowNumber"] = (i + 1).ToString();
                   
                    NotifyDataSetChanged();
                    
                }

            }
            public DataTable get_dt_final()
            {
                DataTable final_dt = summary_Requests.Copy();
                return final_dt;
            }
            public override int ItemCount
            {
                get { return summary_Requests.Rows.Count; }
            }
            // Raise an event when the item-click takes place:
            void OnClick(int position)
            {
                if (ItemClick != null)
                    ItemClick(this, position);
                // user.req_pos = position;


            }
         
        }

and this is the code of the swiping that is written in the same fragment, i'll show you the code before the work around and after it:

  public class SwipeToDeleteCallback : ItemTouchHelper.SimpleCallback
        {
            private View v;
            private DataTable dt;
            private Context context;
        
            public static RecyclerView.Adapter mAdapter;
            private Android.Graphics.Drawables.Drawable deleteIcon;
            private int intrinsicWidth;
            private int intrinsicHeight;
            private Android.Graphics.Drawables.ColorDrawable background;
            private Color backgroundColor;
            private Paint clearPaint;
            private recyclerviewAdapter mdapter;
            private RecyclerView rcv;
            public SwipeToDeleteCallback(int dragDirs, int swipeDirs, Context context) : base(dragDirs, swipeDirs)
            {
                this.context = context;
                deleteIcon = ContextCompat.GetDrawable(context, Resource.Drawable.delete_icon);
                intrinsicWidth = 60;
                intrinsicHeight = 60;
                background = new Android.Graphics.Drawables.ColorDrawable();
                backgroundColor = Color.ParseColor("#f44336");
                clearPaint = new Paint();
                clearPaint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.Clear));
            }

            public SwipeToDeleteCallback(int dragDirs, int swipeDirs, Context context,recyclerviewAdapter mRecyclerView,DataTable dt,RecyclerView rcv) : this(dragDirs, swipeDirs, context)
            {
                this.context = context;
                this.rcv = rcv;
                this.mdapter = mRecyclerView;
                this.dt = dt;
                deleteIcon = ContextCompat.GetDrawable(context, Resource.Drawable.delete_icon);
                intrinsicWidth = 60;
                intrinsicHeight = 60;
                background = new Android.Graphics.Drawables.ColorDrawable();
                backgroundColor = Color.White;
                clearPaint = new Paint();
                clearPaint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.Clear));
            }

            public override int GetMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder)
            {
                if (viewHolder.AdapterPosition == 10)
                {
                    return 0;
                }
                return base.GetMovementFlags(recyclerView, viewHolder);
            }

            public override void OnChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
            {
                base.OnChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }

            public override bool OnMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target)
            {
                //throw new NotImplementedException();
                return false;
            }

            public override void OnChildDrawOver(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
            {
                var itemView = viewHolder.ItemView;
                var itemHeight = itemView.Bottom - itemView.Top;
                var isCanceled = dX == 0f && !isCurrentlyActive;

                if (isCanceled)
                {
                    clearCanvas(c, itemView.Right + dX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
                    base.OnChildDrawOver(c, recyclerView
                        , viewHolder, dX, dY, actionState, isCurrentlyActive);
                    return;
                }
                background.Color = backgroundColor;
                background.SetBounds(itemView.Right + (int)dX, itemView.Top, itemView.Right, itemView.Bottom);
                background.Draw(c);

                var deleteIconTop = itemView.Top + (itemHeight - intrinsicHeight) / 2;
                var deleteIconMargin = (itemHeight - intrinsicHeight) / 2;
                var deleteIconLeft = itemView.Right - deleteIconMargin - intrinsicWidth;
                var deleteIconRight = itemView.Right - deleteIconMargin;
                var deleteIconBottom = deleteIconTop + intrinsicHeight;

                deleteIcon.SetBounds(deleteIconLeft, deleteIconTop, deleteIconRight, deleteIconBottom);
                deleteIcon.Draw(c);

                base.OnChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }

            private void clearCanvas(Canvas c, float v, float top, float right, float bottom)
            {
                c.DrawRect(v, top, right, bottom, clearPaint);
            }

            public override void OnSwiped(RecyclerView.ViewHolder viewHolder, int direction)
            {
                mdapter.RemoveItem(viewHolder.AdapterPosition);
                mdapter.NotifyDataSetChanged();
              
            }

            public override void ClearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder)
            {
                base.ClearView(recyclerView, viewHolder);
            }
        }
    }
}

and this is the solution that i found:

  public class SwipeToDeleteCallback : ItemTouchHelper.SimpleCallback
        {
            private View v;
            private DataTable dt;
            private Context context;
        
            public static RecyclerView.Adapter mAdapter;
            private Android.Graphics.Drawables.Drawable deleteIcon;
            private int intrinsicWidth;
            private int intrinsicHeight;
            private Android.Graphics.Drawables.ColorDrawable background;
            private Color backgroundColor;
            private Paint clearPaint;
            private recyclerviewAdapter mdapter;
            private RecyclerView rcv;
            public SwipeToDeleteCallback(int dragDirs, int swipeDirs, Context context) : base(dragDirs, swipeDirs)
            {
                this.context = context;
                deleteIcon = ContextCompat.GetDrawable(context, Resource.Drawable.delete_icon);
                intrinsicWidth = 60;
                intrinsicHeight = 60;
                background = new Android.Graphics.Drawables.ColorDrawable();
                backgroundColor = Color.ParseColor("#f44336");
                clearPaint = new Paint();
                clearPaint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.Clear));
            }

            public SwipeToDeleteCallback(int dragDirs, int swipeDirs, Context context,recyclerviewAdapter mRecyclerView,DataTable dt,RecyclerView rcv) : this(dragDirs, swipeDirs, context)
            {
                this.context = context;
                this.rcv = rcv;
                this.mdapter = mRecyclerView;
                this.dt = dt;
                deleteIcon = ContextCompat.GetDrawable(context, Resource.Drawable.delete_icon);
                intrinsicWidth = 60;
                intrinsicHeight = 60;
                background = new Android.Graphics.Drawables.ColorDrawable();
                backgroundColor = Color.White;
                clearPaint = new Paint();
                clearPaint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.Clear));
            }

            public override int GetMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder)
            {
                if (viewHolder.AdapterPosition == 10)
                {
                    return 0;
                }
                return base.GetMovementFlags(recyclerView, viewHolder);
            }

            public override void OnChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
            {
                base.OnChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }

            public override bool OnMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target)
            {
                //throw new NotImplementedException();
                return false;
            }

            public override void OnChildDrawOver(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
            {
                var itemView = viewHolder.ItemView;
                var itemHeight = itemView.Bottom - itemView.Top;
                var isCanceled = dX == 0f && !isCurrentlyActive;

                if (isCanceled)
                {
                    clearCanvas(c, itemView.Right + dX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
                    base.OnChildDrawOver(c, recyclerView
                        , viewHolder, dX, dY, actionState, isCurrentlyActive);
                    return;
                }
                background.Color = backgroundColor;
                background.SetBounds(itemView.Right + (int)dX, itemView.Top, itemView.Right, itemView.Bottom);
                background.Draw(c);

                var deleteIconTop = itemView.Top + (itemHeight - intrinsicHeight) / 2;
                var deleteIconMargin = (itemHeight - intrinsicHeight) / 2;
                var deleteIconLeft = itemView.Right - deleteIconMargin - intrinsicWidth;
                var deleteIconRight = itemView.Right - deleteIconMargin;
                var deleteIconBottom = deleteIconTop + intrinsicHeight;

                deleteIcon.SetBounds(deleteIconLeft, deleteIconTop, deleteIconRight, deleteIconBottom);
                deleteIcon.Draw(c);

                base.OnChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }

            private void clearCanvas(Canvas c, float v, float top, float right, float bottom)
            {
                c.DrawRect(v, top, right, bottom, clearPaint);
            }

            public override void OnSwiped(RecyclerView.ViewHolder viewHolder, int direction)
            {
                //Invoke Removing Item method from 
               
               
                int position = viewHolder.LayoutPosition;
                mdapter.RemoveItem(viewHolder.AdapterPosition);
               
                mdapter = new recyclerviewAdapter(myreq, laborers_dt_total, myreq.selected_data);
                rcv.SetAdapter(mdapter);
                var swipeHandler = new SwipeToDeleteCallback(0, ItemTouchHelper.Left, context, mdapter, laborers_dt_total, rcv);
                var itemTouchHelper = new ItemTouchHelper(swipeHandler);
                itemTouchHelper.AttachToRecyclerView(rcv);

            }

            public override void ClearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder)
            {
                base.ClearView(recyclerView, viewHolder);
            }
        }
    }
}

i redefined the adapter for the recyclerview to work it out. i don't get it, why doesn't the mdapter.NotifyDataSetChanged(); work after i add new items. i am sorry for the long post. thanks in advance.

this is a link conveying my problem when i only use mdapter.NotifyDataSetChanged(); when i choose in the first time and delete rows. it works fine. but when i add new items and delete again, it doesn't. https://1drv.ms/v/s!ApO-CpoDPS4ikW3m0I_9X_pcmf8G?e=SZjH1v

rana hd
  • 355
  • 3
  • 18
  • `but when i add items to the recyclerview, then open my list and add new items to my recyclerview, the swiping doesn't work properly.` Sorry, I couldn't understand your meaning by above words. Could you please post a small video and a basic demo to elaborate on your problem? – Jessie Zhang -MSFT Aug 10 '21 at 09:13
  • thanks a lot for replying. i'm trying to add a video but i only get images option. where do i find the video uploading? – rana hd Aug 11 '21 at 11:38
  • You can post your video or demo to onedriver and share link here. – Jessie Zhang -MSFT Aug 12 '21 at 02:44
  • thanks a lot for telling me how. i have shared the link of the video conveying the problem when i only use ```mdapter.NotifyDataSetChanged();``` please let me know if the video is working – rana hd Aug 12 '21 at 13:06
  • It is difficult for us to reproduce the problem based solely on the code you post. Could you please post a basic demo? – Jessie Zhang -MSFT Aug 16 '21 at 08:58
  • i have actually added a video illustrating my problem. it is in the link: https://1drv.ms/v/s!ApO-CpoDPS4ikW3m0I_9X_pcmf8G?e=SZjH1v. i editted my question as i mentioned in the comment just above yours – rana hd Aug 16 '21 at 12:05
  • What's the `laborers_dt_total` and `laborers_dt_total`? Is `itemcode` the new field you added? I don't quite understand the logic of function `OnActivityResult`. Could you please post the code of this fragment page? – Jessie Zhang -MSFT Aug 18 '21 at 09:43
  • @JessieZhang-MSFT i use ```OnActivityResult``` to get the result after closing the dialog fragment corresponding to the list of items. so i get the selected items from it. i will write a simple code to show everything that is going on and share it. please bear with me – rana hd Aug 19 '21 at 14:23
  • @JessieZhang-MSFT hello, this is the link of the code: https://1drv.ms/u/s!ApO-CpoDPS4ikW_rjjJ1Y4X8l6JR?e=Y3Q84z please let me know if it's opening well – rana hd Aug 19 '21 at 17:30

1 Answers1

0

From the following code,we found that variable selected_data is the data to be presented.

RecyclerviewAdapter = new recyclerviewAdapter(this, laborers_dt_total, selected_data);

But after removing the seleted item by swiping the item, you didn't remove the selected data from list selected_data,which is why the data is not actually deleted.

So,you can remove the seleted item from list selected_data after you delete one item.

Please refer the following code:

        public void RemoveItem(int position)
        {
            if (laborers_dt_total.Rows.Count != 0)
            {
                if (position <= laborers_dt_total.Rows.Count && position > -1)  
                {
                    laborers_dt_total.Rows.RemoveAt(position);

                    NotifyDataSetChanged();

                } 
                else
                {
                    Toast.MakeText(context.Context, "select an item to delete", ToastLength.Long).Show();
                }

            }
            else if (laborers_dt_total.Rows.Count == 0)
            {
                Toast.MakeText(context.Context, "no items to delete", ToastLength.Long).Show();

            }
           

            for (int i = 0; i < laborers_dt_total.Rows.Count; i++)
            {
                laborers_dt_total.Rows[i]["rowNumber"] = (i + 1).ToString();

                NotifyDataSetChanged();
            }

            // update variable selected_data
            selected_data.Clear();
            foreach (DataRow row in laborers_dt_total.Rows)
            {
                string rowNumber = row["rowNumber"].ToString();
                string _name = row["name"].ToString();

                string _unit = row["itemsunitcode"].ToString();
                string _quantity = row["itemQty"].ToString();
                string _itemcode = row["itemcode"].ToString();

                selected_data.Add(new list_item {id= Int32.Parse(rowNumber), name= _name ,  unit =_unit, quantity=_quantity, code= _itemcode, IsSelected= true});
            }

            NotifyDataSetChanged();
        }
Jessie Zhang -MSFT
  • 9,830
  • 1
  • 7
  • 19
  • thanks a lot for helping me. i added the code as you recommended, but the recyclerview still doesn't refresh itself when swiping to delete in the second time. the rows don't rearrange themselves and the delete icon stays visible :( – rana hd Aug 21 '21 at 08:30
  • I am confused with the field `rowNumber` of your DataTable and field `id` of class `list_item`, do they correspond to the same value? And I found after remove one item, the value of filed `id` of the rest of the items is not the same value. – Jessie Zhang -MSFT Aug 25 '21 at 09:46
  • no. actually the id and the rowNumber are not related. i don't actually use the id i just defined it arbitrary in case i needed it later. but the rowNumber is essential for me to specify the order of items in the recyclerview. it is the position of the items in the recyclerview (in which row the item is) – rana hd Aug 25 '21 at 11:59
  • Could you please tell me what does the inner codes do : ` for (int i = 0; i < laborers_dt.Rows.Count; i++)` in function `OnActivityResult`? – Jessie Zhang -MSFT Aug 27 '21 at 09:31
  • yes. i am trying to prevent any item repetition in the recyclerview. so if the user chose an item and added it to the recyclerview then opened the list and chose the same item, it won't be added. so i'm comparing the item code of each item in the laborers_dt with the item codes found in the laborers_dt_total( which values will be imported in the recyclerview). if the code already exits in the latter, it will not be added to it. – rana hd Aug 27 '21 at 11:09
  • Since you want to select items from `list_fragment` page and display on page `Fragment1`,why not use the same item model? This will ease the data conversion between page `list_fragment` and `Fragment1`. In addition, you can use `List` not `DataTable` to store the data list in `Fragment1` which will make the data easier to display. – Jessie Zhang -MSFT Sep 01 '21 at 08:29
  • thanks a lot. i'm sorry would you please explain to me what you mean by use the same model. i use the datatable because after the user finishes selecting the items he needs, i save the data in an sql server database table using a stored procedure that takes a User-Defined Table Type as parameter. so i pass the datatable to it. – rana hd Sep 02 '21 at 14:14
  • I mean you can use `List` not `DataTable` to store the data list in `Fragment1`. When you select items from `list_fragment ` page, you can just pass data from `list_fragment ` page back to `Fragment1`. In this condition, you don't need to convert data from type `List` to type `DataTable `. – Jessie Zhang -MSFT Sep 03 '21 at 09:22