Skip to content
Advertisement

Why does the Recycleview work differently when I start it or when I go back to it from an other activity?

I try to create a Shopping/ToDoList application where the items are contained in SharedPreferences. When I start the application, and I choose what I want to execute, Shopping list part or ToDoList part, then the java code fetches the existing data from the SharedPreferences and give to the RecycleView to create and show a list. It seems works totally correct, but if I push the “add” button, then a new Activity is executed where I can specify the items, and when I click the save button, then the java code safe to the SharedPreferences and close the Activity and goes back to the “list” activity where the list should appears again with the new item. But when one data is inserted not in order in SharedPreferences but between two older data then the list create method get crazy and repeat always only the last data from SharedPreferences. But when I close the application, and restart, or goes back to the Main activity where I can choose again which list part I want then the list is totally OK again.

That is the list creating java code:

JavaScript

Here is the code where I can specify the item:

JavaScript

and here is the RecyclerView code:

JavaScript

So the problem is in casef of only where the data is not in order in SharedPreferences and I go back from a new activity.

Please help me if you can, where should I fix my application? Thanks in advance!!!

Advertisement

Answer

When you return to the list after adding an item, you reread all the items from the SharedPreferences in StartDisplay() (which is called from onResume(). This changes the data that the adapter is working with. However, you didn’t tell the adapter that the data has changed. The adapter caches the Views and you must tell it when you modify the data, otherwise it doesn’t know the data has changed. Add the following to StartDisplay() which will invalidate the adapter’s cache and ensure that it rebuilds all the views:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement