如何检查SharedPreferences文件是否存在

18

我正在查找android Shared Preferences,想知道是否有一种方法只是检查首选项文件是否存在。

   SharedPreferences  mySharedPreferences ; 
mySharedPreferences=getSharedPreferences(“Name_of_your_preference”,mode);

根据上面的代码,我认为"Name_of_Your_preference"被存储为一个文件或某种容器,其中包含您的首选项。

我想知道是否有一种方法可以检查它是否存在。当用户加载活动时,我想将所有设置保存到此文件中,并使用一些默认值(关闭所有设置)。但是,我只想在他们第一次访问页面时才这样做。

否则,如果每次加载页面时都执行此操作,会怎么样?

SharedPreferences.Editor editor= mySharedPreferences.edit();

/* now store your primitive type values. In this case it is true, 1f and Hello! World  */

editor.putBolean(“myBoolean”,true);

editor.putFloat(“myFloat”,1f);

editor.putString(“myString”,” Hello! World”);

我猜它会覆盖所有设置,即使是他们设置的设置。

8个回答

28

SharedPreferences保存在一个XML文件中。你可以在 /data/data/你的应用包名/shared_prefs/Name_of_your_preference.xml 找到它。

要检查SharedPreferences 'Name_of_your_preference'是否存在:

File f = new File(
"/data/data/your_application_package/shared_prefs/Name_of_your_preference.xml");
if (f.exists())
    Log.d("TAG", "SharedPreferences Name_of_your_preference : exist");
else
    Log.d("TAG", "Setup default preferences");

致敬。


那我只需要通过模拟器浏览吗? - chobo2
你怎么进入那个文件夹? - meda
f.exists() 导致了我的应用程序崩溃。即使添加了 try catch,异常也没有被捕获...它只是崩溃了。 - arun8
新文件(“/data/data/your_application_package/shared_prefs/Name_of_your_preference.xml”);除非它抛出异常,否则这将始终计算为true,对吗? 因为你正在创建一个新文件,而不是检查它是否已经存在。 注意:这是一个带有思考的问题。 - Curtes Malteser
1
new File() 不会创建新文件。要创建文件,需要使用 f.createNewFile() - FinalSpirit

20

您可以在 SharedPreferences 对象上使用 contains 方法来检查您的偏好键是否存在于文件中。 如果返回 false,则可以假设这是第一次,并填充默认设置。 关于此方法的文档位于这里

我找不到任何方法来检查偏好文件是否已经存在(它将在您第一次检索编辑器时自动创建),但是这种方法应该可以解决问题。


3
如果我使用getAll(),它只会获取“Name_of_your_preference”的首选项,那怎么样?所以如果计数为零,我猜它就不会创建了? - chobo2
应该也能正常工作。我想这只是个人偏好的问题,但在getAll()的情况下,您必须实例化一个Map对象才能检查其大小。原始方法似乎只是一个更快的布尔测试。 - Eugene S
我正在使用Monodroid。它有一个计数函数,所以我认为我没问题。 - chobo2

7

我没有足够的回复来评论natur3的帖子。所以这个答案。

@natur3: 非常有帮助,谢谢。但是我遇到了一个小问题...文件后缀名。如果我像这样定义我的文件名:

    private static final String FILENAME = "myPrefs";

然后使用:

    File f = new File("/data/data/" + getPackageName() +  "/shared_prefs/" + FILENAME);

f.exists()方法即使文件在文件系统中存在也会返回false。这是因为在写入SharedPreferences时,Android会自动添加“.xml”后缀,所以我必须将我的文件引用看起来像这样:

    File f = new File("/data/data/" + getPackageName() +  "/shared_prefs/" + FILENAME + ".xml");

为了使其工作,我不知道您从哪里得到了"_preferences.xml"后缀。

我通过在Eclipse中浏览模拟器文件系统并选择“Window-> Show View-> Other ...”,然后选择“File Explorer”来解决了这个问题。


4

不要硬编码“/data/data/”路径,你可以这样做:

public boolean preferenceFileExist(String fileName) {
    File f = new File(getApplicationContext().getApplicationInfo().dataDir + "/shared_prefs/"
            + fileName + ".xml");
    return f.exists()
}

注意:在新版Android上,getApplicationInfo().dataDir返回/data/user/0 - Abandoned Cart

1

我这样做是因为我认为它是可适应的。

File f = new File("/data/data/" + getPackageName() +  "/shared_prefs/" + getPackageName()+ "_preferences.xml");

if(f.exists())
{ 
     //do stuff`enter code here`
}

我在onCreate中使用了这个验证过程,用于检查首选项是否存在,根据答案启用一个按钮来清除首选项或不清除 - 只需在DDMS中验证首选项文件的名称是否手动命名即可。


嗨natur3,文件路径应该是这样写的:File f = new File("/data/data/" + getPackageName() + "/shared_prefs/_preferences.xml"); 没有第二个getPackageName()。当我使用你的代码时,它会进入一个不存在的目录,因此无法保存。 - Dan Tarlow

0

看起来这是一个更精确的解决方案

val file = File(filesDir.parent, "shared_prefs/name_of_preference.xml")

或者只是

val file = File(filesDir, "../shared_prefs/name_of_preference.xml")

0
我发现最简单的方法是,我们可以通过 Android 上的内置代码检查共享首选项是否存在。
 sharePrefName.contains(String key) // as if (userData.contains("name")){Toast // Your data is already here!}

检查偏好设置中是否包含某个偏好项。(这是一个抽象的公共布尔方法)

简单易懂 :)


0

我的解决方案如下:


/**
 * Returns the shared preferences directory.
 */
val Context.sharedPrefsDir get() = File(filesDir.parentFile, "shared_prefs")

/**
 * Check if the SharedPreferences file exists in the shared preferences directory
 */
fun Context.settingsFileExists(file: String) = File(sharedPrefsDir, "$file.xml").exists()

/**
 * Opens the shared preferences as by getSharedPreferences if it exists,
 * but does NOT create the file if it does not yet exist.
 */
fun Context.getSharedPreferencesOrNull(file: String, mode: Int = Context.MODE_PRIVATE) =
        if(settingsFileExists(file))
            getSharedPreferences(file, mode)
        else
            null

这使我能够说出像这样的话

val myPrefs = Context.getSharedPreferencesOrNull("alternativeConfigFile") ?: Context.getSharedPreferences("mainConfigFile")

在不让 Android 在幕后创建 "alternativeConfigFile.xml" 的情况下。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接