簡體   English   中英

如何檢查 SharedPreferences 文件是否存在

[英]How to check if SharedPreferences file exists or not

我正在尋找一個 android 共享首選項,我想知道是否有一種方法可以檢查首選項文件是否存在。

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

上面的代碼讓我相信“Name_of_Your_preferene”被存儲為一個文件或某種包含您的偏好的容器。

我想知道是否可以檢查它是否存在。 當用戶加載一個活動時,我想用一些默認值(所有設置關閉)將所有設置保存到這個文件中。 但是,我只想在他們第一次訪問該頁面時這樣做。

否則,如果我每次加載頁面時都做這樣的事情

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”);

我猜它會覆蓋所有設置,甚至是他們設置的設置。

SharedPreferences 保存在一個 xml 文件中。 您可以在 /data/data/your_application_package/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");

問候。

您可以使用SharedPreferences對象上的contains方法來檢查文件中是否存在您的首選項鍵之一。 如果返回false ,您可以假設這是第一次並填充默認設置。 此方法的文檔在此處

我找不到任何方法來檢查首選項文件是否已經存在(它會在您第一次檢索編輯器時自動創建),但是這種方法應該可以解決問題。

我沒有足夠的代表來評論 natur3 的帖子。 因此這個答案。

@natur3:非常有幫助,謝謝。 但是,我遇到了一個小問題......文件后綴。 如果我這樣定義我的文件名:

    private static final String FILENAME = "myPrefs";

然后使用:

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

即使文件存在於文件系統中,f.exists() 也會返回 false。 這是因為 Android 在編寫 SharedPreferences 時會自動添加“.xml”后綴,所以我必須使我的文件引用看起來像這樣:

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

讓它工作。 我不知道你從哪里得到你的“_preferences.xml”后綴。

我設法通過使用 Window->Show View->Other... 在 Eclipse 中瀏覽模擬器文件系統來解決這個問題,然后選擇“文件資源管理器”。

您可以這樣做,而不是硬編碼“/data/data/”路徑:

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

我是這樣做的,因此它具有適應性。

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

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

如果首選項存在與否,我在 onCreate 的驗證過程中使用了它,並根據答案啟用按鈕以清除首選項 - 如果未手動命名,只需驗證 DDMS 中首選項文件的名稱。

我發現的最簡單的方法是,我們可以通過 android 上的內置代碼檢查共享首選項是否存在

 sharePrefName.contains(String key) // as if (userData.contains("name")){Toast // Your data is already here!}

檢查首選項是否包含首選項。 (它是抽象的布爾公共方法)

簡單易行:)

這似乎是一個更准確的解決方案

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

要不就

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

我的解決方案:


/**
 * 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”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM