【问题标题】:Error saving using SharedPreferences使用 SharedPreferences 保存时出错
【发布时间】:2013-02-18 17:17:59
【问题描述】:

我正在使用 sharedpreferences 保存一些变量,但我的保存方法使应用程序崩溃并出现空指针异常。

public void save() {

    SharedPreferences sp = context.getSharedPreferences(saveFile, Context.MODE_PRIVATE);
    //Use the editor for easier management, no calling edit and commit so many times. 
    SharedPreferences.Editor editor = sp.edit();

    editor.putInt("X", player.getX());
    editor.putInt("Y", player.getY());
    editor.putInt("level", player.getLevel());
    editor.putFloat("xp", player.getXp());
    editor.commit();
}

getSharedPreferences() 本身不起作用,需要有上下文。在它之前,这可能是一个问题。我已经定义了上下文,导入了 SharedPreferences,为什么这不起作用?

编辑:这里是 logcat

02-18 20:21:49.958: E/AndroidRuntime(1005): FATAL EXCEPTION: Thread-89
02-18 20:21:49.958: E/AndroidRuntime(1005): java.lang.NullPointerException
02-18 20:21:49.958: E/AndroidRuntime(1005): at com.package.game.GameScreen.save(GameScreen.java:856)
02-18 20:21:49.958: E/AndroidRuntime(1005): at com.package.game.GameScreen.updateLevelUp(GameScreen.java:364)

save方法如上及行:

SharedPreferences sp = context.getSharedPreferences(saveFile, Context.MODE_PRIVATE);

是第 856 行。updateLevelUp 是当玩家升级和退出该屏幕时调用的方法,游戏恢复并调用 save()。

【问题讨论】:

  • 发布堆栈跟踪。哪一行是空的?
  • 考虑保存对safeFile.edit() 的引用并调用commit() 一次。
  • "loadSave" 在逻辑上似乎为空
  • @EvZ 可能是contextplayers,甚至可能是返回值之一。
  • @Sam true ,答案很快。

标签: android sharedpreferences


【解决方案1】:

您的context 变量是null。确保它已被初始化,并且您没有在各自的ContextonCreate() 之前调用此代码。

【讨论】:

  • 抱歉,我要设置成什么?
  • @user2005938 将其设置为您的活动或应用程序上下文。或者更好的是,直接在其位置使用getApplicationContext()
  • 如何将其设置为应用程序上下文? getApplicationContext() 对我不起作用。
  • 无论如何你都可以使用context = getApplicationContext() 来设置它。你说它对你不起作用是什么意思?你在哪里调用这个代码?
  • 当我做 Context context = getApplicationContext();它说 getApplicationContext 方法未定义。
【解决方案2】:

作为一个很好的规则,您希望在管理 SharedPreferences 时使用SharedPreferences.Editor

这里有一个更简单的方法:

public void save() {
    SharedPreferences saveFile = context.getSharedPreferences(loadSave, Context.MODE_PRIVATE);
    //Use the editor for easier management, no calling edit and commit so many times. 
    SharedPreferences.Editor editor = saveFile.edit();

    editor.putInt("x", player.get());
    editor.putInt("Y", player.getY());
    editor.putInt("level", player.getLevel());
    editor.putFloat("xp", player.getXp());

    //Save changes now
    editor.commit();
}

此外,如果您在执行此操作后仍然获得空指针,请确保您发布日志以便我们可以追踪异常。

【讨论】:

  • 这是一个很好的提示,但我认为它不会改变任何东西。
  • 首先,他没有发布日志,这意味着我们甚至无法确定问题所在。乍一看,我发现唯一有问题的是多次调用 edit() 和 commit(),大多数情况下,commit() 调用是导致问题的常见原因。
猜你喜欢
  • 2012-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
相关资源
最近更新 更多