When I develop an android app, I run into the exception which I do not have any clue; I have googled related topics but none of them helped.
Fatal Exception: java.util.ConcurrentModificationException
java.util.HashMap$HashIterator.nextEntry (HashMap.java:806)
java.util.HashMap$KeyIterator.next (HashMap.java:833)
com.android.internal.util.XmlUtils.writeSetXml (XmlUtils.java:298)
com.android.internal.util.XmlUtils.writeValueXml (XmlUtils.java:447)
com.android.internal.util.XmlUtils.writeMapXml (XmlUtils.java:241)
com.android.internal.util.XmlUtils.writeMapXml (XmlUtils.java:181)
android.app.SharedPreferencesImpl.writeToFile (SharedPreferencesImpl.java:596)
android.app.SharedPreferencesImpl.access$800 (SharedPreferencesImpl.java:52)
android.app.SharedPreferencesImpl$2.run (SharedPreferencesImpl.java:511)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1112)
java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:587)
java.lang.Thread.run (Thread.java:841)
The ConcurrentModificationException generally occurs when working with Java Collections. The Collection classes in Java are very fail-fast and if they are attempted to be modified while a thread is iterating over it, a ConcurrentModificationException is thrown.
If you use classical for loop with the index or enhanced for loop and try to remove an element from the ArrayList using remove() method, you will get the ConcurrentModificationException but if you use Iterator's remove method or ListIterator's remove() method, then you won't get this error and be able to remove the ...
Since Iterator of HashMap is fail-fast it will throw ConcurrentModificationException if you try to remove entry using Map.
Preferences are thread safe(!), but not process safe. The answer of @mohan mishra simply not true, no need to synchronize everything. The problem here, as statet out in another question is, that per documentation you MUST NOT modify any instance that is returned by getStringSet and getAll
getStringSet()
Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.
getAll()
Note that you must not modify the collection returned by this method, or alter any of its contents. The consistency of your stored data is not guaranteed if you do.
To the other question
Documentation
Please ensure that you are not accessing the preferences from any type of background thread. Also all your methods to add to preference must be synchronised(if you have your own preference managing class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With