Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/180.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何检查SharedReference是否存在_Android_Sharedpreferences - Fatal编程技术网

Android 如何检查SharedReference是否存在

Android 如何检查SharedReference是否存在,android,sharedpreferences,Android,Sharedpreferences,我用这种方式检查文件是否存在,但我需要超越它,我需要知道是否有一个特定的文件,有什么办法吗 File f = new File("/data/data/com.eventrid.scanner/shared_prefs/Eventrid.xml"); if (f.exists()){ } else{ } SharedReferences有一个contains(字符串键)方法,可用于检查具有给定键的条目是否存

我用这种方式检查文件是否存在,但我需要超越它,我需要知道是否有一个特定的文件,有什么办法吗

File f = new File("/data/data/com.eventrid.scanner/shared_prefs/Eventrid.xml");
          if (f.exists()){

          }
          else{

          }  

SharedReferences
有一个
contains(字符串键)
方法,可用于检查具有给定键的条目是否存在

好吧,我们可以:

    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);
}
这是因为存储在/data/data/myApp/shared_prefs/myApp_prefrences.xml中的首选项文件仅在其值已设置时才包含首选项的值对。

您可以尝试此操作

 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.

你检查文件了吗?难道没有一个
contains
方法吗?方法不作为一种方式存在,我的想法也不是读取文件,我只是想知道是否有更简单的方法。你想从文件中提取信息而不读取它?我只想知道是否有首选项,我不在乎值,如果存在,我重定向到另一个布局,非常感谢你!他帮了我很多忙!正是我需要的