为什么我的SharedPreferences在单击按钮时不保存?

时间:2019-02-11 07:03:04

标签: android sharedpreferences

因此,我尝试向SharedPreferences中添加一些值,但是每次单击按钮时,它都与默认值00一起使用,因此即使if语句不应该,其if语句也始终返回true t。

private static final String SHARED_FREFS = "sharedPrefs";
private static final String STATE = "state";

这是按钮单击事件

public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences(SHARED_FREFS, MODE_PRIVATE);
                SharedPreferences.Editor editor =  sharedPreferences.edit();

                int currentTime = Calendar.getInstance().getTime().getMinutes();
                String eh = sharedPreferences.getString(STATE,  "00");

                if(!Integer.toString(currentTime).equalsIgnoreCase(sharedPreferences.getString(STATE,  "00"))){
                    GetData();
                    editor.putString(STATE, Integer.toString(currentTime));
                    Log.e("ATTENTION!:", "METHOD HAS BEEN FIRED!");
                }
            }
        });

我正在尝试将当前分钟存储在其中,但没有这样做。 我是否需要一个名为data的文件夹,其中包含一个名为sharedPrefs的xml文件?

3 个答案:

答案 0 :(得分:5)

  

为什么单击按钮后我的SharedPreferences不保存?

因为您忘记了将更新保存在SharedPreferences

editor.apply();

中添加数据之后,您需要使用 editor.commit(); SharedPreferences

示例

public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences(SHARED_FREFS, MODE_PRIVATE);
                SharedPreferences.Editor editor =  sharedPreferences.edit();

                int currentTime = Calendar.getInstance().getTime().getMinutes();
                String eh = sharedPreferences.getString(STATE,  "00");

                if(!Integer.toString(currentTime).equalsIgnoreCase(sharedPreferences.getString(STATE,  "00"))){
                    GetData();
                    editor.putString(STATE, Integer.toString(currentTime));
                    editor.apply();
                    Log.e("ATTENTION!:", "METHOD HAS BEEN FIRED!");
                }
            }
        });

答案 1 :(得分:3)

更新sharePrefs上的所有内容后,总是在编辑器上使用commitapply

mEditor.commit();

答案 2 :(得分:3)

正如我所看到的那样,在共享首选项编辑器中添加数据后,总是需要使用editor.commit()editor.apply()。应该使用哪一个,请参见下文:

    apply() vs commit();

    commit(): this method runs synchronously means,
    1.  thread safe.
    2. slow.
    and always gives feed back but 
    apply():  this method runs asynchronously means.
    1. no thread safe.
    2. runs fast.
    and does not give feedback.
Finally sharedPreferences instances are singleton with in a process it's safe to replace any instance of commit() with apply(), if you were already ignoring the return value.

根据您的要求使用。