How does SharedPreferences differ from a static global variable of one class?

本小妞迷上赌 提交于 2019-12-12 10:22:13

问题


I have interpreted the following about SharedPreferences and have a bit of doubt of what they are capable of. Here is what I found:

Android SharedPreferences are used for the globalization of a variable so that throughout the application we can use SharedPreferences to store and retrieve data instead of defining static variables in one class and let the class be used to retrieve the variables throughout the app.

Can someone explain whether this is correct. If there are major differences that I'm missing please let me know. Thanks.


回答1:


When saving sharedpreferences, the android system just creates a new xml file in your app directory holding those values. So if your app gets killed those variables will be saved. And the variables are always readable from any activity because they are stored in a file.

When storing sharedpreferences you use a key (final static String) to access them later, maybe that key is what they mean when talking about static's

small example:

Static:

public static final String PREFS_NAME = "settings"
public static final String SILENT_MODE = "silentMode";

In any activity of your app:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean(SILENT_MODE, false);

Edit from: http://developer.android.com/guide/topics/data/data-storage.html#pref




回答2:


You use SharedPreferences to save and retrieve any primitive data. Unlike the Static variables approach, this data will persist across user sessions even if your application is killed.



来源:https://stackoverflow.com/questions/12624671/how-does-sharedpreferences-differ-from-a-static-global-variable-of-one-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!