Android 如何检查 SharedPreferences 是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22821270/
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
How to check if SharedPreferences exists or not
提问by Nico1991
I'm checking in this way if the file exists, but I need to go beyond, I need to know if there is one in specific, is there any way?
我用这种方式检查文件是否存在,但我需要超越,我需要知道是否有一个具体的,有什么办法吗?
File f = new File("/data/data/com.eventrid.scanner/shared_prefs/Eventrid.xml");
if (f.exists()){
}
else{
}
回答by Yjay
SharedPreferences
has a contains(String key)
method, which can be used to check if an entry with the given key exists.
SharedPreferences
有一个contains(String key)
方法,可用于检查具有给定键的条目是否存在。
http://developer.android.com/reference/android/content/SharedPreferences.html
http://developer.android.com/reference/android/content/SharedPreferences.html
回答by Chris Sprague
Well, one could do:
嗯,可以这样做:
SharedPreferences sharedPrefs = getSharedPreferences("sp_name", MODE_PRIVATE);
SharedPreferences.Editor ed;
if(!sharedPrefs.contains("initialized")){
ed = sharedPrefs.edit();
//Indicate that the default shared prefs have been set
ed.putBoolean("initialized", true);
//Set some default shared pref
ed.putString("myDefString", "wowsaBowsa");
ed.commit();
}
回答by Juan José Melero Gómez
Another solution:
另一种解决方案:
If you know the exact number of preferences you have you can:
如果您知道您拥有的确切偏好数量,您可以:
public void isPreferencesSet(Context context){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return (sharedPreferences.getAll().size() == exactNumberOfPreferences);
}
This works because the preferences file stored in /data/data/myApp/shared_prefs/myApp_prefrences.xml contains a preference's value pair only if its value has been set.
这是有效的,因为存储在 /data/data/myApp/shared_prefs/myApp_prefrences.xml 中的首选项文件仅在其值已设置时才包含首选项的值对。
回答by Cyd
You can try this
你可以试试这个
fun checkLoginInfo(): Boolean{
val saveLogin = sharedPreferences.getBoolean(SAVE_LOGIN, false)
return saveLogin
}
Checks whether the preferences contains a preference.
@param(SAVE_LOGIN) key The name of the preference to check.
@param(false) default
@return Returns true if the preference exists in the preferences, otherwise false.