我用这种方式检查文件是否存在,但我需要更进一步,我需要知道是否有特定的文件,有没有办法?
File f = new File("/data/data/com.eventrid.scanner/shared_prefs/Eventrid.xml");
if (f.exists()){
}
else{
}
我用这种方式检查文件是否存在,但我需要更进一步,我需要知道是否有特定的文件,有没有办法?
File f = new File("/data/data/com.eventrid.scanner/shared_prefs/Eventrid.xml");
if (f.exists()){
}
else{
}
SharedPreferences
类中有一个contains(String key)
方法,可以用于检查是否存在具有给定键的条目。
http://developer.android.com/reference/android/content/SharedPreferences.html
好的,可以这样做:
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();
}
另一种解决方案:
如果你知道你拥有的偏好数量,你可以:
public void isPreferencesSet(Context context){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return (sharedPreferences.getAll().size() == exactNumberOfPreferences);
}
检查SharedPreferences键是否存在:
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
if(mPrefs.getAll().containsKey("KeyName")){
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.