11

I have a RecyclerView - Grid, with drag & drop, using this code I've manage to achieve that, And made a lot of changes, only one problem, i can't save the dragged items position on restarting ( the app not the phone ). What i thought about is adding " int position " to my item.java constructor, but what i can't do is getting the changed position .

I'm using the same drag & drop codes provided in the link.

    ItemTouchHelper.Callback _ithCallback = new ItemTouchHelper.Callback() {
    //and in your imlpementaion of
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        // get the viewHolder's and target's positions in your adapter data, swap them
        Collections.swap(AllItems, viewHolder.getAdapterPosition(), target.getAdapterPosition());
        // and notify the adapter that its dataset has changed

        rcAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        //TODO
    }

    //defines the enabled move directions in each state (idle, swiping, dragging).
    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
                ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.START | ItemTouchHelper.END);
    }
};

Here's the code in onCreate :

    ItemTouchHelper ith = new ItemTouchHelper(_ithCallback);
    ith.attachToRecyclerView(RcView);

Getting Duplicated items after position changing, Code :

    @Override
public void onStop()
{
    super.onStop();
    SharedPreferencesTools.setOrderedItems(this, AllItems);
}

getAllItemList :

private List<Item> getAllItemList(){
AllItems = SharedPreferencesTools.getOrderedItems(this);
//Add item .. etc 
//return items 

}

Community
  • 1
  • 1
Jaeger
  • 1,646
  • 8
  • 27
  • 59
  • A Bumb to the post maybe? – Jaeger Jan 29 '16 at 22:39
  • Just to note, the positions are automatically added, not set manually . – Jaeger Feb 04 '16 at 02:51
  • Have I undestood correctly, that you want to persist `AllItems` state between app's runs, right? – Konstantin Loginov Feb 04 '16 at 08:59
  • I have 7 items, every added item got a position based on where have been it added, Like WiF in Position 0, Bluetooth Position 1, the user will long press and modify the place, Now .. the user will kill the app, when he gets back, the positions will be reset and return to the defaults, What i want is to keep the changed positions . – Jaeger Feb 04 '16 at 11:23
  • Ok, I gotcha. Then see my answer below :-) – Konstantin Loginov Feb 04 '16 at 11:41

1 Answers1

8

Just keep your modified collection AllItems in SharedPreferences and load it on the app start & store it back, once you get out of the app.

To do this, you need to serialize your collection to json by Gson and store as a String. And then deserialize it afterwards:

public final class SharedPreferencesTools {
    private static final String USER_SETTINGS_PREFERENCES_NAME = "UserSettings";
    private static final String ALL_ITEMS_LIST = "AllItemsList";
    private static Gson gson = new GsonBuilder().create();

    public static List<Item> getOrderedItems(Context context) {
        String stringValue = getUserSettings(context).getString(ALL_ITEMS_LIST, "");
        Type collectionType = new TypeToken<List<Item>>() {
        }.getType();
        List<Item> result = gson.fromJson(stringValue, collectionType);
        return (result == null) ? new ArrayList<Item>() : result;
    }

    public static void setOrderedItems(Context context, List<Item> items) {
        String stringValue = gson.toJson(items);

        SharedPreferences sharedPreferences = getUserSettings(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(ALL_ITEMS_LIST, stringValue);
        editor.apply();        
    }

    static SharedPreferences getUserSettings(Context context) {
        return context.getSharedPreferences(USER_SETTINGS_PREFERENCES_NAME, Context.MODE_PRIVATE);
    }
}

The usage of these two methods:

 SharedPreferencesTools.setOrderedItems(getActivity(), AllItems);
 ...
 List<Item> AllItems = SharedPreferencesTools.getOrderedItems(getActivity());
Konstantin Loginov
  • 15,802
  • 5
  • 58
  • 95
  • Just ran into a weird problem, When i change the positions, the items will get duplicated in the next round, What's wrong ? I've used the " setOrderedItems" inside ItemTouchHelper method. – Jaeger Feb 05 '16 at 02:40
  • I've changed this return (result == null) ? new ArrayList() : result to "result" only, And I'm getting NullpointerException, So my guess is, It's returning null => making a new list, => saving it to shared preferences, => restarting => again it's getting null, and making a new list, that's why it's duplicated, But Why it's returning null every time? – Jaeger Feb 05 '16 at 03:08
  • @AboHani you can save your list in `onPause()` of the `Activity`/`Fragment` and restore in `onResume()`. If it doesn't help - post the code somewhere and I'll try to figured out :-) – Konstantin Loginov Feb 05 '16 at 08:22
  • It's a service, Why ? SmallApp API use a service to run a small app ( from Sony ), It's the same in onCreate/onStop, Updated . – Jaeger Feb 05 '16 at 14:18