Not getting the updated value of the shared preference in the service

a 夏天 提交于 2019-11-30 17:19:58

问题


I am storing some value to a shared preference from an activity which launched from a widget. If I retrieve that value from the service started from the same widget, it is not the updated one. I am getting the previous value had in the shared preference. Even i check that value in the shared preference xml, i sees the updated one there. Why this is happening. I know that widget and activity are two process, is that the reason?​

SharedPreferences preferences = getSharedPreferences("preferences_target_value", Context.MODE_PRIVATE);

String targetValue = preferences.getString("preferences_target_value", "0");

System.out.println("targetValue "+targetValue);`

回答1:


These values are cached per process.

If you are running on Android > 2.3 you must specify MODE_MULTI_PROCESS when you call getSharedPreferences (). If you are running on Android < 2.3 then it should just work correctly. If you are running on Android 2.3 then there is a bug in the shared preferences stuff and it doesn't work correctly across multiple processes no matter what you do.




回答2:


use commit() after updating values, call this to have any changes you perform in the Editor

prefsEditor.commit();

change your code instead of this

SharedPreferences preferences = getSharedPreferences("preferences_target_value", Context.MODE_PRIVATE);

to this

SharedPreferences preferences = getSharedPreferences("preferance name", Context.MODE_PRIVATE);



回答3:


In manifest file try removing

android:process=":my_process"

from service. Hope it will work.



来源:https://stackoverflow.com/questions/12136677/not-getting-the-updated-value-of-the-shared-preference-in-the-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!