【问题标题】:Android refuses to write/create sharedpreferences fileAndroid 拒绝写入/创建 sharedpreferences 文件
【发布时间】:2011-04-23 15:52:20
【问题描述】:

我正在使用 Eclipse 3.5.2 IDE 进行 Android 开发。我正在使用以下代码写入默认的 sharedpreferences 文件,并在 adb emulator 中运行它:

private SharedPreferences getOurSharedPreferences(Activity act) {
    // return getSharedPreferences(SHARED_PREFS_FILENAME, MODE_PRIVATE);
    return act.getPreferences(MODE_PRIVATE);
}

private void putStringToStorage(Activity act, String keyName, String s) {

    // Store it.
    SharedPreferences sharedPrefs = getOurSharedPreferences(act);
    SharedPreferences.Editor editor = sharedPrefs.edit();
    editor.remove(keyName);
    // editor.putString(keyName, s);
    editor.putString(keyName, "test123");
    boolean bCommitted = editor.commit();
    if (!bCommitted) 
        throw new RuntimeException("(AndroidApplication) Unable to save new string.");

    // Get it back as a test.
    // String s2 = getStringFromStorage(keyName);
}

上述方法属于我的一个Application子类,这就是为什么该方法带有一个Activity对象参数以便我可以访问Activity .getPreferences()。请注意,以前我使用的是全局 getSharedPreferences() 调用,但由于遇到的问题,我出于绝望而改为 getPreferences()。我写“test123”而不是变量“s”的原因是为了确保我遇到的问题与“”的某些值无关s”,也许共享首选项文件可能不喜欢。

每当我运行代码 editor.commit() 总是返回 FALSE。一些历史。不久前,我能够使用名为“app_global”的共享首选项文件写入共享首选项文件,该文件是通过使用全局 getSharedPreferences() 调用而不是 Activity.getPreferences()。我能够从该共享首选项文件中写入和读取值,但是,每当我重新启动我的应用程序时,我在上次会话中写入的值都消失了。作为调试工作的一部分,我进入了 adb shell 并从我的应用程序的 shared_prefs 文件夹中删除了“app_global”。从那以后,模拟器似乎不愿意创建新的共享首选项文件,无论是默认文件还是其他文件。

注意,LogCat 窗口始终为空,Console 窗口不显示任何错误,包括在模拟器中启动我的应用程序期间。我还尝试在调试配置中选中“擦除用户数据”以调试模式启动应用程序。这也无济于事。从 adb 执行“ls -a”时,无论我做什么 editor.commit() 都会失败,并且我的应用程序的 shared_prefs 文件夹shell 总是空的

我的问题是:

  • 我在某处顺便读到关于“重建用户图像”的模拟器。这是一种我可以用来尝试解决共享首选项存储问题的技术吗?如果是这样,我该怎么做?

  • 我还有什么办法可以解决这个问题吗?

-- 罗施勒

【问题讨论】:

  • 附注:抛出 RuntimeException 并不是一个好习惯。
  • 你有没有试过在 editor.remove(keyName); 之后使用 commit() ?
  • 不,但我解决了这个问题。请参阅下面的“自我回复”。谢谢。

标签: android emulation commit adb sharedpreferences


【解决方案1】:

我设法通过手动重新创建 sharedpreferences 文件解决了这个问题。我不能确定这一点,但似乎如果您手动删除属于模拟器的 sharedpreferences 文件,即使您选择“擦除用户数据”选项,它也不会重新创建它。要手动重新创建 sharedpreferences 文件,我执行了以下操作:

  • 加载 ADB 外壳
  • 更改为 sharedpreferences 文件夹(请注意,您必须运行模拟器,否则您将收到“device not found”错误,假设您也没有连接手机)
  • 使用您在代码中使用的 sharedpreferences 文件的名称创建一个空文件。就我而言,我创建了一个名为“app_global”的文件。

您可以在此处找到 sharedpreferences 文件夹:

/data/data/your.app.package.name/shared_prefs

your.app.package.name 是您的应用程序的包名称。要从 ADB shell 中创建空文件,我使用了以下命令:

echo -n >app_global

其中“app_global”是您为 sharedpreferences 文件命名的任何内容。 -n 选项可防止将换行符放入文件中。如果您使用 getPreferences(),则默认 sharedpreferences 文件的名称为“your.app.package.name_preferences.xml”。

我从这篇 StackOverflow 帖子中获得了有关 sharedpreferences 文件夹的信息:

How to examine SharedPreferences from adb shell?

-- 罗施勒

【讨论】:

    猜你喜欢
    • 2016-04-10
    • 2018-11-07
    • 2012-07-12
    • 2023-04-01
    • 2021-07-28
    • 2020-03-28
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多