【问题标题】:Shared Preference data not cleared when activity is closed活动关闭时未清除共享首选项数据
【发布时间】:2018-03-21 18:18:47
【问题描述】:

在我的应用程序中,我使用了地点选择器。地点选择器提供的数据使用共享首选项发送到 3 个不同的活动。并在 TextView 中显示此数据。问题是当我关闭活动并再次打开该活动时,我的数据仍然可见在 TextView 中。即使我在 onDestroy() 中清除了它。

这是我从地点选择器发送数据的代码:

            SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("city_address", (String) cityAddress);
            editor.putString("city_name", (String) city);
            editor.commit();

            Intent intent = new Intent(this, CleanlinessActivity.class);
            startActivity(intent);

在 CleanlinessActivity 的 onCreate() 中使用此代码设置数据

     SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
    String n = settings.getString("city_name", "Enter Location");
    String a = settings.getString("city_address", "");
    cityname.setText(n);
    cetlocation.setText(a);

我在 CleanlinessActivity 中使用此代码清除了数据

     @Override
protected void onDestroy() {
    super.onDestroy();
    SharedPreferences settings = getSharedPreferences("city_address", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.remove("city_address");
    editor.clear().commit();
}

【问题讨论】:

  • 您不应该在 onDestroy() 中这样做。 onDestroy() 并不是每次都打电话。也可以使用单个SharedPreferences,不需要使用其中的两个。对于您的回答,editor.clear().commit(); 将完成这项工作。
  • 发布完整的活动代码
  • 似乎问题是,您的第一个代码正在插入数据,并且在您启动应用程序时正在执行
  • 测试用例:稍后尝试调用super.onDestroy(),因为sharedPrefs使用不同的线程......直到它被正确执行可能是上下文被清除!如果有效就更新!!我会发布答案! editor.clear().commit(); super.onDestroy();
  • 我不知道如何,但现在它与我的代码完美配合。我没有对我的代码做任何事情。LOL

标签: android sharedpreferences


【解决方案1】:

关闭应用意味着只需单击主页按钮,然后永远不会调用 onDestroy(),您可以重温 Android 生命周期 here 如果您正在做的只是单击主页按钮,则考虑将您的代码移动到onStop(),否则您需要在remove(...) 之后commit() android 文档指出“在编辑器中标记应删除首选项值,一旦调用 commit(),这将在实际的首选项中完成。"

【讨论】:

    【解决方案2】:

    你有一个名为 city_address 的 SharedPreferences 实例,它有两个字段或(如果我们称之为列),但在 onDestroy()你试图只清除它的一个字段 city_address 和另一个字段 city_name 字段保持不变,如果要完全删除 city_address SharedPreferences 的内容,请使用editor.clear().commit(); 或``editor.clear().apply();`

    【讨论】:

      猜你喜欢
      • 2020-11-28
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多