【问题标题】:SharedPreferences not updating value when returning to Activity, but only keeps initial Activity load valueSharedPreferences 在返回 Activity 时不更新值,而只保留初始 Activity 加载值
【发布时间】:2014-03-28 21:48:03
【问题描述】:

所以我尝试使用 SharedPreferences 将值从 Activity 传递给 Class。问题如下:

在初始加载 Activity 时,该值存储在 SharedPreferences 中,但如果我退出 Activity 并返回并尝试更新该值,SharedPreferences 似乎没有更新并停留在Activity 的初始加载。

一些类函数

private void populatePlayerQueue(){
        int category_index;
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getContext());
        category_index = sharedPreferences.getInt("selected_category", 0);
    }

Activity onResume

@Override
public void onResume() {
    super.onResume();
    int tmp = Integer.parseInt(getIntent().getStringExtra("CategoryIndex"));
    //store the category in the shared preferences
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt("selected_category", tmp);
    editor.commit();
}

我想做的事:

我必须将一个整数从活动发送到特定的类,如果我回到活动,那么我需要存储更新值,这样该类将能够再次访问新更新的值。我只能访问上下文而不是活动。如果我尝试创建接口回调以与活动通信,这会导致错误。所以这个选项被取消了,因此我正在尽我所能做到这一点。

【问题讨论】:

  • 提供更多信息,你想要实现什么

标签: java android android-activity sharedpreferences


【解决方案1】:

为了获得更好的结果,在退出应用程序时通过其键删除 SharedPreference。

在您退出应用程序时,只需清除 SharedPreference 即可:

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("selected_category"); //Just remove it by its specific key
editor.commit();

然后,当您在同一个键上返回应用程序时,它会清楚地再次加载并保存新值,或者您可以使用新值。

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多