如何从 Android 中的 PreferenceActivity 获取 SharedPreferences?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2614719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:34:19  来源:igfitidea点击:

How do I get the SharedPreferences from a PreferenceActivity in Android?

androidpreferencespreferenceactivitysharedpreferences

提问by Dave

I am using a PreferenceActivity to show some settings for my application. I am inflating the settings via a xml file so that my onCreate (and complete class methods) looks like this:

我正在使用 PreferenceActivity 来显示我的应用程序的一些设置。我正在通过 xml 文件扩充设置,以便我的 onCreate(和完整的类方法)如下所示:

public class FooActivity extends PreferenceActivity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        addPreferencesFromResource(R.xml.preference);
    }
}

The javadoc of PreferenceActivityPreferenceFragmentstates that

PreferenceActivity PreferenceFragment的 javadoc指出

These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android.content.Context) with a context in the same package as this activity.

当用户与它们交互时,这些首选项将自动保存到 SharedPreferences。要检索此活动中的首选项层次结构将使用的 SharedPreferences 实例,请使用与此活动相同的包中的上下文调用 getDefaultSharedPreferences(android.content.Context)。

But how I get the name of the SharedPreference in another Activity? I can only call

但是我如何在另一个活动中获得 SharedPreference 的名称?我只能打电话

getSharedPreferences(name, mode)

in the other activity but I need the name of the SharedPreference which was used by the PreferenceActivity. What is the name or how can i retrieve it?

在另一个活动中,但我需要 PreferenceActivity 使用的 SharedPreference 的名称。名称是什么或我如何检索它?

回答by Pentium10

import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);

Update

更新

According to Shared Preferences | Android Developer Tutorial (Part 13)by Sai Geetha M N,

根据共享首选项 | 由 Sai Geetha MN 编写的Android 开发者教程(第 13 部分)

Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.

Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.

许多应用程序可以提供一种方法来捕获用户对特定应用程序或活动设置的偏好。为了支持这一点,Android 提供了一组简单的 API。

首选项通常是名称值对。它们可以跨应用程序中的各种活动存储为“共享首选项”(注意目前它不能跨进程共享)。或者它可以是需要存储特定于活动的东西。

  1. Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.

  2. Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.

  1. 共享首选项:应用程序的所有组件(活动、服务等)都可以使用共享首选项。

  2. 活动处理首选项:这些首选项只能在特定活动中使用,不能由应用程序的其他组件使用。

Shared Preferences:

共享首选项:

The shared preferences are managed with the help of getSharedPreferencesmethod of the Contextclass. The preferences are stored in a default file (1)or you can specify a file name (2)to be used to refer to the preferences.

getSharedPreferencesContext类的方法的帮助下管理共享首选项。首选项存储在默认文件(1) 中,或者您可以指定用于引用首选项的文件名(2)

(1) The recommended wayis to use by the default mode, without specifying the file name

(1)推荐使用默认模式,不指定文件名

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

(2) Here is how you get the instance when you specify the file name

(2) 指定文件名时获取实例的方法如下

public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

MODE_PRIVATEis the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLEand MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLEother application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLEother applications also have write permissions for the created file.

MODE_PRIVATE是首选项的操作模式。这是默认模式,意味着只有调用应用程序才能访问创建的文件。支持的其他两种模式是MODE_WORLD_READABLEMODE_WORLD_WRITEABLE。在MODE_WORLD_READABLE其他应用程序中可以读取创建的文件但不能修改它。如果MODE_WORLD_WRITEABLE其他应用程序也对创建的文件具有写权限。

Finally, once you have the preferences instance, here is how you can retrieve the stored valuesfrom the preferences:

最后,一旦你有了首选项实例,这里是你如何从首选项中检索存储的值

int storedPreference = preferences.getInt("storedInt", 0);

To store valuesin the preference file SharedPreference.Editorobject has to be used. Editoris a nested interface in the SharedPreferenceclass.

必须使用首选项文件对象来存储值SharedPreference.EditorEditor是类中的嵌套接口SharedPreference

SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

Editor also supports methods like remove()and clear()to delete the preference values from the file.

编辑器还支持方法,如remove()clear()从文件中删除偏好值。

Activity Preferences:

活动偏好:

The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences()method of the activity. The getPreferencemethod uses the getSharedPreferences()method with the name of the activity class for the preference file name.

其他应用程序组件可以使用共享首选项。但是,如果您不需要与其他组件共享首选项并希望拥有活动私有首选项,则可以借助getPreferences()活动的方法来实现。该getPreference方法使用getSharedPreferences()带有活动类名称的方法作为首选项文件名。

Following is the code to get preferences

以下是获取首选项的代码

SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);

The code to store values is also the same as in case of shared preferences.

存储值的代码也与共享首选项的情况相同。

SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.

您还可以使用其他方法,例如将活动状态存储在数据库中。注意 Android 还包含一个名为android.preference. 该包定义了实现应用程序首选项 UI 的类。

To see some more examples check Android's Data Storagepost on developers site.

要查看更多示例,请查看开发者网站上的Android数据存储帖子。

回答by Green Oak Software

If you don't have access to getDefaultSharedPreferenes(), you can use getSharedPreferences(name, mode)instead, you just have to pass in the right name.

如果您无权访问getDefaultSharedPreferenes(),则可以getSharedPreferences(name, mode)改用 ,只需传入正确的名称即可。

Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivityonCreate(), and seeing what preferencesNameis.

Android 创建此名称(可能基于您项目的包名称?)。您可以通过将以下代码放入 a 中来获取它SettingsActivityonCreate(),然后查看是什么preferencesName

String preferencesName = this.getPreferenceManager().getSharedPreferencesName();

The string should be something like com.example.projectname_preferences. Hard code that somewhere in your project, and pass it in to getSharedPreferences()and you should be good to go.

字符串应该类似于com.example.projectname_preferences. 在你的项目中的某个地方硬编码,并将它传递给getSharedPreferences()你应该很高兴。

回答by kc ochibili

Declare these methods first..

先声明这些方法..

public static void putPref(String key, String value, Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.commit();
}

public static String getPref(String key, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
}

Then call this when you want to put a pref:

然后在您想放置首选项时调用它:

putPref("myKey", "mystring", getApplicationContext());

call this when you want to get a pref:

当你想获得一个偏好时调用它:

getPref("myKey", getApplicationContext());

Oryou can use this object https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbowhich simplifies everything even further

或者你可以使用这个对象https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo这进一步简化了一切

Example:

例子:

TinyDB tinydb = new TinyDB(context);

tinydb.putInt("clickCount", 2);
tinydb.putFloat("xPoint", 3.6f);
tinydb.putLong("userCount", 39832L);

tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true); 

tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);

回答by hamish

having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...

必须到处传递上下文真的很烦我。代码变得过于冗长且难以管理。我在每个项目中都这样做......

public class global {
    public static Activity globalContext = null;

and set it in the main activity create

并将其设置在主活动中创建

@Override
public void onCreate(Bundle savedInstanceState) {
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
            global.sdcardPath,
            ""));
    super.onCreate(savedInstanceState);

    //Start 
    //Debug.startMethodTracing("appname.Trace1");

    global.globalContext = this;

also all preference keys should be language independent, I'm shocked nobody has mentioned that.

所有首选项键都应该与语言无关,我很震惊没有人提到这一点。

getText(R.string.yourPrefKeyName).toString()

now call it very simply like this in one line of code

现在在一行代码中非常简单地调用它

global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);

回答by UrviG

if you have a checkbox and you would like to fetch it's value ie true / false in any java file--

如果您有一个复选框并且您想在任何 Java 文件中获取它的值,即 true/false--

Use--

用 -

Context mContext;
boolean checkFlag;

checkFlag=PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(KEY,DEFAULT_VALUE);`

回答by Ali Asadi

Updated 2019

2019 年更新

You can simply use PowerPreferencelibrary

您可以简单地使用PowerPreference

https://github.com/AliEsaAssadi/Android-Power-Preference

https://github.com/AliEsaAssadi/Android-Power-Preference

Getting shared preference instance

获取共享首选项实例

To get the default instance you just need to call

要获得默认实例,您只需要调用

PowerPreference.getDefaultFile()

Or if you want a specific preference file

或者如果你想要一个特定的首选项文件

PowerPreference.getFileByName(fileName)

Writing Data:

写入数据:

PowerPreference.getDefaultFile().put(key,value)

Getting Data

获取数据

PowerPreference.getDefaultFile().getString(key,value)

回答by Istiak

Try following source code it worked for me

尝试遵循对我有用的源代码

//Fetching id from shared preferences
    SharedPreferences sharedPreferences;
    sharedPreferences =getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
    getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");