SharedPreferences always get default value in my existing app but when created new app its ok

后端 未结 11 963
眼角桃花
眼角桃花 2020-12-16 13:18

SharedPreferences doesn\'t work correct in one existing apps. I tried many different ways but still not working. Always get default values app start again.

  • It\
11条回答
  •  忘掉有多难
    2020-12-16 13:43

    Instead of using edit.commit();, you should use edit.apply();. Apply will update the preference object instantly and will save the new values asynchronously, so allowing you to read the latest values.

    Source - Also read detailed difference between commit() and apply() in this SO Post.

    The "Source" post referenced above also states pretty much the same problem and switching to apply() seems to have resolved the issue there.

    Problem statement in the referenced post:

    The problem is that when I am accessing this values, it is not returning updated values, it gives me a value of SharedPreferences.

    But when I am confirming the data in XML file ,the data updated in that.

    PS: And the reason that the same code block is not working on this one app and working on all other apps could also be that you are either using the block at different places or updating the value somewhere else too.

提交回复
热议问题