Save new positions in Room after recyclerView drag & drop

放肆的年华 提交于 2019-12-23 04:48:12

问题


I've implemented a recyclerView with a drag and drop feature in my app. Everything works fine until the app is relaunched --any drag and drop changes were not saved/remembered by the app.

I've tried:

  • Using SharedPreference + GSON
  • Reading other SQLite answers here on SO like this one: Store new position of RecyclerView items in SQLite after being dragged and dropped
  • Reading Paul Burke's Medium Post

My current code looks like this:

In onCreate

 ItemViewModel itemViewModel = ViewModelProviders.of(this).get(ItemViewModel.class);
    itemViewModel.getAllItems().observe(this, new Observer<List<Item>>() {
        @Override
        public void onChanged(List<Item> items) {

         adapter.setItemList(items);
         itemList = items; //Global variable itemList


        }
    });

The method called when item is dragged/moved

private void swap(int firstPosition, int secondPosition) {
    Collections.swap(itemList, firstPosition, secondPosition);
        for(int i = 0; i < itemList.size(); i++) {
            Item currentItem = itemList.get(i);
            ItemViewModel.update(currentItem );
        }
        adapter.notifyItemMoved(firstPosition, secondPosition);
     }

Any ideas how I can let my app save the reordered recyclerView after drag and drop? Thanks in advance.


回答1:


If you wish to preserve the order of your items once you close your app or move to another activity, you will need to add a property to your entity files which will server as an order value for it. Once added, you could access your dao and run an UPDATE SQL in the Collections.swap method when reordering items and than on every load of the list, return the items ordered by that property.



来源:https://stackoverflow.com/questions/53297253/save-new-positions-in-room-after-recyclerview-drag-drop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!