Search code examples
android-recyclerviewxamarin.androidsaving-data

Xamarin.Android how to remember the position of items in a recyclerview


I have a recyclerview set up in xamarin.android as per the code in this link

https://www.appliedcodelog.com/2019/08/reorder-list-items-by-drag-and-drop-in.html

My question is, how can I remember the position of these items when the app is restarted etc. When the user adds items they are inserted at adapter position 0,1,2,3 etc but when they close the app and come back in, it is not always in the same order.

The user can also rearrange by drag and drop so this seems to add even more confusion!

Currently I have the items in the recyclerview being saved by converting the list to Json and loading when the app opens again but as I said, the items aren't always in the same order as before the app was closed.

Can anyone advise the best way to do this? I have tried to add the item name and position number to a list converting to json then trying to insert the item at the saved position index but can't get it to work..

Thanks


Solution

  • Do you want to achieve the result like following GIF?

    enter image description here

    You can use PreferenceManager to store position of items(Before store data, I will Serialize data) in a recyclerview.

    You can override OnPause() method, this method will be executed when application is background or app is killed. So we can store the position and data in this method.Here is code about ReOrderActivity

       [Activity(Label = "ReOrderList")]
        public class ReOrderActivity : Activity, IOnStartDragListener
        { 
            private ItemTouchHelper _mItemTouchHelper;
            public static ObservableCollection<string> ResourceList;
            private RecyclerView _resourceReorderRecyclerView;
            ReOrderAdapters resourceAdapter;
            ISharedPreferences prefs;
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                SetContentView(Resource.Layout.ReOrderLayout);
                prefs = PreferenceManager.GetDefaultSharedPreferences(this);
                GetCollection();
    
                 resourceAdapter = new ReOrderAdapters(ResourceList, this);
    
                // Initialize the recycler view.
                _resourceReorderRecyclerView = FindViewById<RecyclerView>(Resource.Id.ResourceReorderRecyclerView);
    
                Button mDone = FindViewById<Button>(Resource.Id.mDone);
                mDone.Click += MDone_Click;
                _resourceReorderRecyclerView.SetLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.Vertical, false));
                _resourceReorderRecyclerView.SetAdapter(resourceAdapter);
                _resourceReorderRecyclerView.HasFixedSize = true; 
    
                ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(resourceAdapter);
                _mItemTouchHelper = new ItemTouchHelper(callback);
                _mItemTouchHelper.AttachToRecyclerView(_resourceReorderRecyclerView);
            }
            protected override void OnPause()
            {
                base.OnPause();
                string ConvertData = JsonConvert.SerializeObject(ResourceList);
                ISharedPreferencesEditor editor = prefs.Edit();
                editor.PutString("ObservableCollection_ConvertData", ConvertData);
    
                // editor.Commit();    // applies changes synchronously on older APIs
                editor.Apply();        // applies changes asynchronously on newer APIs
            }
    
            private void MDone_Click(object sender, System.EventArgs e)
            {
    
                resourceAdapter.AddItem("Add item");
            }
    
            public void OnStartDrag(RecyclerView.ViewHolder viewHolder)
            {
                _mItemTouchHelper.StartDrag(viewHolder);
            }
    
            //Added sample data record here
            public void GetCollection()
            {
                //ISharedPreferencesEditor editor = prefs.Edit();
                //editor.PutString("ObservableCollection_ConvertData", "");
                //editor.Apply();     
                string ConvertData =  prefs.GetString("ObservableCollection_ConvertData","");
                if(string.IsNullOrEmpty(ConvertData))
                {
                    ResourceList = new ObservableCollection<string>();
                    ResourceList.Add("OnPause()");
                    ResourceList.Add("OnStart()");
                    ResourceList.Add("OnCreate()");
    
                }
                else
                {
                    ResourceList= JsonConvert.DeserializeObject<ObservableCollection<string>>(ConvertData);
                }
    
                //var or= ResourceList.ToString();
            }
        }
    }
    
    

    You can download my demo https://drive.google.com/file/d/1mQTKf3rlcIVnf2N97amrqtnrSCRk-8ZW/view?usp=sharing