【问题标题】:How to check if SharedPreferences exists or not如何检查 SharedPreferences 是否存在
【发布时间】:2014-05-14 07:34:45
【问题描述】:

我这样检查文件是否存在,但是我需要超越,我需要知道是否有一个具体的,有什么办法吗?

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

          }
          else{

          }  

【问题讨论】:

  • 您查看文档了吗?不是有contains方法吗?
  • 方法不存在作为一种方式,我的想法也是不读取文件,我只是想知道是否有更简单的方法。
  • 您想从文件中提取信息而不读取它?
  • 我只是想知道是否有偏好,我不在乎值,如果存在我重定向到另一个布局,

标签: android sharedpreferences


【解决方案1】:

SharedPreferences 有一个contains(String key) 方法,可用于检查具有给定键的条目是否存在。

http://developer.android.com/reference/android/content/SharedPreferences.html

【讨论】:

  • 非常感谢!对我帮助很大!
  • 正是我需要的
【解决方案2】:

嗯,可以这样做:

    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();
    }  

【讨论】:

    【解决方案3】:

    另一种解决方案:

    如果您知道确切的偏好数量,您可以:

    public void isPreferencesSet(Context context){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        return (sharedPreferences.getAll().size() == exactNumberOfPreferences);
    }
    

    这是因为存储在 /data/data/myApp/shared_prefs/myApp_prefrences.xml 中的首选项文件仅在其值已设置时才包含首选项的值对。

    【讨论】:

      【解决方案4】:

      你可以试试这个

       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.
      

      【讨论】:

        【解决方案5】:

        检查 SharedPreferences 键是否存在:

            SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
            if(mPrefs.getAll().containsKey("KeyName")){
        

        【讨论】:

          猜你喜欢
          • 2011-10-21
          • 2022-01-21
          • 1970-01-01
          • 1970-01-01
          • 2014-01-07
          • 2011-08-23
          • 2012-02-29
          • 2020-07-05
          • 1970-01-01
          相关资源
          最近更新 更多