简体   繁体   English

如何在多个片段文件中使用共享首选项

[英]how to use shared preferences in multiple fragment files

I need to use shared preferences in multiple fragment files (cant use activity files) I have to store several string lines. 我需要在多个fragment文件(不能使用的活动文件)中使用共享的首选项,我必须存储几行字符串。

How do I initialize shared preferences in my fragments? 如何在片段中初始化shared preferences How do I write / read to it? 如何写/读它?

Do I need to initialize it in my main activity or do I have to initialize it in my fragment activity files? 我是否需要在主活动中对其进行初始化,还是必须在片段活动文件中对其进行初始化?

Tricks like: 技巧如:

Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE); 

... doesn't work. ...不起作用。

Try to encapsulate your SharedPreferences in some preferences class, similar to this: 尝试将您的SharedPreferences封装在一些首选项类中,类似于:

class MyPrefs {

    private static final String FILENAME = "prefs_filename";
    private static final String KEY_SOMETHING = "something";

    private SharedPreferences mPreferences;

    public MyPrefs(Context context) {
        mPreferences = new SharedPreferences(FILENAME, Context.MODE_PRIVATE);
    }

    public void setSomething(Something value) {
       mPreferences.edit().put...(KEY_SOMETHING, value).commit();
    }

    public Something getSomething() {
       return mPreferences.getSomething(key, defaultValue);
    }
}

This way we provide clean API for our non-volatile data storage. 这样,我们为非易失性数据存储提供了干净的API。 SharedPreferences is too low-level, exposing too many details, such as storage file name and it forces us to remember all keys and value types to extract any data. SharedPreferences级别太低,暴露了太多细节,例如存储文件名,这迫使我们记住所有键和值类型以提取任何数据。 It may work in simple cases, but as soon as your stored data becomes complex, it creates tons of problems. 在简单的情况下,它可能会起作用,但是一旦您存储的数据变得复杂,就会产生很多问题。 Try storing something like a user profile with few fields or a simple complex number and you'll get the idea. 尝试存储诸如用户配置文件之类的内容,其中包含很少的字段或简单的复数,您就会明白。 Using raw SharedPreferences will make your refactoring royal pain. 使用原始的SharedPreferences将使您SharedPreferences重构。 Even simple data format upgrade (like schema update) will quickly become impossible with naked SharedPreferences . 裸露的SharedPreferences即使是简单的数据格式升级(如模式更新)也将很快变得不可能。

Using profiles should be stored in an SQL database, not shared preferences. 使用配置文件应存储在SQL数据库中,而不是共享首选项中。 Hence the name. 由此得名。 A database stores data, preferences store preference values. 数据库存储数据,首选项存储首选项值。 You can't complain about an API when you are misusing it. 滥用API时,您不必抱怨。

Start with SQLite documentation 从SQLite文档开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM