Preference wont change in my main activity

In my MainActivity I have a textView. In that textView there is a Number that I keep in a SharedPreferences. and every couple of min The SharedPreferences is changed with an alarm manager, but the SharedPreferences in my MainActivity wont change, anyone has an idea why?

this is a part of The code in the MainActivity

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    int ReleaseDate = preferences.getInt("com.fisher.freedom.ReleaseDate", 0);
    TextView edit = (TextView) findViewById(R.id.DaysLeft);

    Toast.makeText(MainActivity.this, "" + preferences.getInt("com.fisher.freedom.ReleaseDate", 0), Toast.LENGTH_SHORT).show();
    edit.setText("" + ReleaseDate);

This is the code in the AlarmReceiver

    public static final String ReleaseDate_Key = "com.fisher.freedom.ReleaseDate";

    @Override
    public void onReceive(Context context, Intent intent) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        int ReleaseDate = preferences.getInt(ReleaseDate_Key, 0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt(ReleaseDate_Key, --ReleaseDate);
        editor.apply();




For get the value of your int use this:

SharedPreferences sharedPreferences = getSharedPreferences(getApplicationContext().getPackageName(),0);
int ReleaseDate = sharedPreferences.getInt("ReleaseDate",0);

And to save it use this:

SharedPreferences prefs = getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
prefs.edit().putInt("ReleaseDate", ReleaseDate).commit();

With this you forget about writing on static variable your package name, it worked for me, so it's going for you.

链接地址: http://www.djcxy.com/p/50606.html

上一篇: 通过使用SharedPreferences在ListView中保存ToggleButton状态

下一篇: 偏好不会改变我的主要活动