在活动之间使用共享的首选项 [英] Using shared preferences in between activities

查看:46
本文介绍了在活动之间使用共享的首选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在项目的两个活动之间共享一个共享的首选项,但是由于某种原因,我无法传递数据.

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.

http://developer.android.com/reference/android/preference/PreferenceManager.html#getDefaultSharedPreferences(android.content.Context)

这篇关于在活动之间使用共享的首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆