【发布时间】: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