【问题标题】:How to get contents of SharedPreferences file and overwrite them?如何获取 SharedPreferences 文件的内容并覆盖它们?
【发布时间】:2012-03-02 14:28:04
【问题描述】:

我对 Android 开发很陌生。我在这里浏览 API http://developer.android.com/reference/android/content/SharedPreferences.html

但我对如何实际获取文件内容并从中读取或写入感到困惑。

我有这段代码来获取 SharedPreferences 对象:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( MyClassName.this);

但在这种情况下,我获得了对 sharedPreferences 的引用,但没有连接到存储首选项数据的文件。

也许我没有正确理解 API,但我应该如何获取对文件的引用并对其进行读/写?

谢谢!

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    如果您想从必须使用的 SharedPreferneces 中获取值(此示例适用于字符串,但您也可以调用 getBoolean、getInt 等。)

    prefs.getString("myString", "defaultValue"); // "defaultValue" will be returned in case "myString" wasn't saved on the SharedPreferences
    

    要存储一些值,您可以这样做:

    prefs.edit()
    .putString("myString", "newValue")
    .putBoolean("working", true)
    .commit();
    

    如您所见,您可以一次编辑多个值..

    【讨论】:

      【解决方案2】:

      edit() 将返回一个编辑器,您必须使用该编辑器来修改 sharedpreferences 文件,当您结束编辑时调用 commit() 以永久进行更改

      【讨论】:

        【解决方案3】:

        但在这种情况下,我获得了对 sharedPreferences 的引用,但没有连接到存储首选项数据的文件。

        SharedPreferences 对象与存储首选项数据的文件有一个“连接”。

        也许我没有正确理解 API,但我应该如何获取对文件的引用并对其进行读/写?

        要读取首选项,请使用 SharedPreferences 上的 getter(例如,getString())。自己编写偏好:

        • 通过在SharedPreferences 对象上调用edit() 来获取SharedPreferences.Editor
        • 使用Editor 上的设置器(例如putString()
        • Editor 上致电apply()(如果可能)或commit() 以保存您的更改

        此外,您还可以(并且在很多情况下应该)使用PreferenceActivity 来允许用户直接查看和修改他们的偏好。

        【讨论】:

          猜你喜欢
          • 2021-11-29
          • 1970-01-01
          • 1970-01-01
          • 2010-12-26
          • 2018-01-18
          • 2013-03-14
          • 1970-01-01
          • 2010-09-20
          • 2016-02-01
          相关资源
          最近更新 更多