簡體   English   中英

返回到Activity時,SharedPreferences不更新值,而僅保留初始Activity加載值

[英]SharedPreferences not updating value when returning to Activity, but only keeps initial Activity load value

因此,我試圖使用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);
    }

簡歷上的活動

@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();
}

我正在嘗試做的是:

我必須將一個整數從活動發送到特定的類,如果我返回到活動,則需要存儲更新值,因此該類將能夠再次訪問新更新的值。 我只能訪問上下文,而不能訪問活動。 如果我嘗試創建接口回調以與活動進行通信,則會導致錯誤。 因此取消了此選項,因此我正在盡一切努力做到這一點。

為了獲得更好的結果,請在退出應用程序時通過其鍵刪除 SharedPreference。

在您退出應用程序的情況下,只需清除SharedPreference即可:

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

然后,當您使用相同的鍵返回到應用程序時,它將清楚地再次加載並保存新值,或者您可以使用新的鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM