在活动之间使用共享的首选项 [英] Using shared preferences in between activities
问题描述
我试图在项目的两个活动之间共享一个共享的首选项,但是由于某种原因,我无法传递数据.
I am trying to share a shared preference in between two activities of my project, but for some reason I am not able to pass the data.
我有活动A读取共享的首选项,活动B读取并编辑该共享的首选项.
I have Activity A which reads the shared preference and Activity B that reads as well as edit that shared preference.
这是我用来在活动B中编写共享首选项的代码:
Here is the code I am using to write the shared preference in Activity B:
SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.
MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("theme", "black");
editor.commit();
并在活动A中阅读:
SharedPreferences sharedPref = getSharedPreferences("myPrefs", Context.
MODE_WORLD_WRITEABLE);
String theme=sharedPref.getString("theme","blue");
我尝试使用不同的模式,并且它在Activity B中以PRIVATE模式工作,但未与Activity A共享.出于某些原因,我认为我对两个不同的活动有两个不同的共享首选项(同名).如何在两个活动中使用相同的共享首选项?
I have tried using the different modes, and it worked in Activity B in PRIVATE mode but it wasn't shared to activity A. For some reasons I think I have two different shared preferences(same name) for the two different activities. How do I use the same shared preference for both the activities ?
推荐答案
在任何活动中,您都可以做得更简单:
You can do simpler - in any activity:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
通过这种方式,您可以在任何地方使用相同的偏好.
You will have the same prefs this way from anywhere.
这篇关于在活动之间使用共享的首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!