When Deleting View With Swipe In Recyclerview Doesn't Deletin In Sharedpreference
Solution 1:
For one, you probably shouldn't be loading the list of favorites from preferences every single time you want to query or modify the list. Instead, query it once when the Activity this RecyclerView belongs to is created (you could do that from the Adapter itself or from the Activity), and store that to a global variable. ie:
classSomeActivityextendsActivity {
private ArrayList<OrderModel> favorites = newArrayList<>();
privateSharedPreferenceprefsHelper=newSharedPreference();
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
//....
favorites.addAll(prefsHelper.loadFavorites(this));
}
}
Then, when you want to change something, modify that ArrayList and then save it directly:
publicvoidaddFavorite(OrderModel model) {
favorites.add(model);
prefsHelper.storeFavorites(this, favorites);
}
You'll probably need to modify this to fit your code, but it's an example of what to do.
What you currently have won't work, because every time you go to modify the list, you're recreating it from a String representation. That means that the list of favorites you have loaded contains completely different instances of the models, even if they contain the same values.
When you pass an OrderModel to your removeFavorite()
method, it's not going to remove anything, because nothing is equal; by reloading the list, you have completely fresh instances.
If you really want to keep your current code structure, switch to indexes instead of passing the object. Or, override equals()
in OrderModel and have it manually compare the values, so even different instances can be matched.
Post a Comment for "When Deleting View With Swipe In Recyclerview Doesn't Deletin In Sharedpreference"