简体   繁体   English

搞乱Android的共享偏好 - 使用哪个功能?

[英]Mess with the shared preferences of android - which function to use?

Here's a standard task: store some values in the application's shared preferences in order to be able to retrieve it later on. 这是一个标准任务:在应用程序的共享首选项中存储一些值,以便以后能够检索它。 But one will discover that there are 3 functions to store a value in there: 但是人们会发现有3个函数可以在那里存储一个值:

//1.
public static SharedPreferences PreferenceManager.getDefaultSharedPreferences(Context context) {}

//2.
public SharedPreferences Activity.getPreferences(int mode) {}

//3.
public SharedPreferences ContextWrapper.getSharedPreferences(String name, int mode) {}

So now here's the question: which one to choose and which one is better or there's a different purpose for each of them? 所以现在问题是:选择哪一个,哪一个更好,或者每个人有不同的目的?

Here's the answer to my own question: 这是我自己的问题的答案:

First, let's take a look at the implementations of those 3 functions. 首先,我们来看看这3个函数的实现。

//1.
public static SharedPreferences PreferenceManager.getDefaultSharedPreferences(Context context) {
    return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());
}

//2.
public SharedPreferences Activity.getPreferences(int mode) {
    return getSharedPreferences(getLocalClassName(), mode);
}

//3.
public SharedPreferences ContextWrapper.getSharedPreferences(String name, int mode) {
    return mBase.getSharedPreferences(name, mode);
}

Here mBase is a reference to an object of type Context. 这里mBase是对Context类型对象的引用。

We see that the 2nd functions calls the 3rd one, and all those 3 functions are basically equivalent but with different parameters. 我们看到第二个函数调用第三个函数,所有这三个函数基本相同但参数不同。 Think of overloading. 想想重载。

Next, going deeper to the 1st function's implementation, we can simplify its call as the following: 接下来,深入了解第一个函数的实现,我们可以简化其调用,如下所示:

//1.
public static SharedPreferences PreferenceManager.getDefaultSharedPreferences(Context context) {
    return context.getSharedPreferences(context.getPackageName() +
        "_preferences", Context.MODE_PRIVATE);
}

and similarly, for the second function: 同样,对于第二个功能:

//2.
public SharedPreferences Activity.getPreferences(int mode) {
    return mBase.getSharedPreferences(getLocalClassName(), mode);
}

To sum-up, the 1st function creates a shared preference file with a name as <your_package_name>_preferences , the 2nd function creates a shared preference file with a name as <your_class_name> , and finally, the 3rd function lets you to specify arbitrary name for the shared preference file. 总而言之,第1个函数创建一个名为<your_package_name>_preferences的共享首选项文件,第二个函数创建一个名为<your_class_name>的共享首选项文件,最后,第三个函数允许您指定任意名称对于共享首选项文件。

Needless to say that you need to specify the correct name for the shared preference file in order to retrieve the saved values back. 不用说,您需要为共享首选项文件指定正确的名称,以便返回保存的值。 So you may use the 3rd function to specify the name yourself or to use the 1st or 2nd function respective to how you have saved it before. 因此,您可以使用第3个函数自己指定名称,或者使用与之前保存方式相对应的第1个或第2个函数。

Warning! 警告! Make sure you are passing the correct instance of the Context class. 确保传递Context类的正确实例。 For example, a messy scenario would look like this: you are saving into shared preferences from a background thread which is running in the system (like for example when using the android's out-of-the-box SyncAdapter framework) and trying to get back the saved values from your UI-thread, you may get the default/wrong values! 例如,一个混乱的场景看起来像这样:你从系统中运行的后台线程保存到共享首选项(例如,当使用android的开箱即用的SyncAdapter框架时)并尝试返回从UI线程中保存的值,您可能会得到默认/错误的值!

Hope this will be helpful for someone else... ;) 希望这对其他人有帮助......;)

I am sharing mine, hope it will make life easy - 我和我分享,希望它会让生活变得轻松 -

    public class SharedPreferenceStore {

    public static void deleteValue(Context context, String key) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        Editor editor = preferences.edit();
        editor.remove(key).apply();
    }

    public static void storeValue(Context context, String key, String value) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        Editor editor = preferences.edit();
        editor.putString(key, value).apply();
    }

    public static void storeValue(Context context, String key, boolean value) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        Editor editor = preferences.edit();
        editor.putBoolean(key, value).apply();
    }

    public static void storeValue(Context context, String key, double value) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String doubleVal = String.valueOf(value);
        Editor editor = preferences.edit();
        editor.putString(key, doubleVal).apply();
    }

    public static void storeValue(Context context, String key, float value) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        Editor editor = preferences.edit();
        editor.putFloat(key, value).apply();
    }

    public static void storeValue(Context context, String key, long value) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        Editor editor = preferences.edit();
        editor.putLong(key, value).apply();
    }

    public static void storeValue(Context context, String key, int value) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        Editor editor = preferences.edit();
        editor.putInt(key, value).apply();
    }

    /*************************
     * GET Methods
     ***************************************/
    public static String getValue(Context context, String key, String defValue) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, defValue);
    }

    public static boolean getValue(Context context, String key, boolean defValue) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getBoolean(key, defValue);
    }

    public static double getValue(Context context, String key, double defValue) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        String doubleVal = String.valueOf(defValue);
        return Double.parseDouble(preferences.getString(key, doubleVal));
    }

    public static float getValue(Context context, String key, float defValue) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getFloat(key, defValue);
    }

    public static long getValue(Context context, String key, long defValue) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getLong(key, defValue);
    }

    public static int getValue(Context context, String key, int defValue) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getInt(key, defValue);
    }
}

Just use the class and forget about all complications of SharedPrefences. 只需使用该课程,忘记SharedPrefences的所有复杂情况。 Hope it will help you :) 希望它能帮到你:)

its one and only method, just different calls and accesibility 它唯一的方法,只是不同的调用和可访问性

  1. "default" means you are not declaring name of XML file storing your data (thats the way that SharedPreferences work) and it will be available from every Activity / Context (lets say "globally") - if you want to keep ony few values you may use this “default”表示您没有声明存储数据的XML文件的名称(这就是SharedPreferences工作方式),并且它可以从每个Activity / Context (简称“全局”)中获得 - 如果您想保留少量值可以用这个
  2. is keeping values available only for calling Acivity - "private" for storing Activity , but be aware about int mode 保持值仅用于调用Acivity - “private”用于存储Activity ,但要注意int mode
  3. the last one is working also "globally" like first one, but in here you may declare file name and keep few files with different kinds of values - dedicated for creating more complicated storing values constructions (some wrappers etc.) 最后一个也像第一个一样工作“全局”,但是在这里你可以声明文件名并保留几个具有不同类型值的文件 - 专用于创建更复杂的存储值构造(一些包装器等)

It depends. 这取决于。 #1 Will return the SharedPreferences for whichever Context you pass it. #1将为您传递的上下文返回SharedPreferences。 #2 Will return the SharedPreferences for the context of the Activity you're in. This may be the same as #1 or it might not. #2将返回您所在Activity的上下文的SharedPreferences。这可能与#1相同,也可能不同。 #3 Will let you break your SharedPreferences up into different groups and name them. #3将让您将SharedPreferences分解为不同的组并命名它们。 This might be a nice way to break things up but I have never actually done it. 这可能是一个很好的方法来解决问题,但我从来没有真正做过。

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

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