Android 偏好新旧值比较
Android Preference old and new value compare
我从 activity1 获得了 NewValue 并按偏好存储并与来自 activity2 的 OldValue 进行比较:我的问题是它不存储 oldValue..
于 activity 1:
int i = 5;
SharedPreferences prefs1 = getPreferences(0);
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putInt("new", i);
editor.commit();
在 activity 2:
SharedPreferences prefs1 = getPreferences(0);
int oldValue = prefs1.getInt("old", 0);
int newValue = prefs1.getInt("new", 0);
/* Should Activity Check for Updates Now? */
if (oldValue < newValue) {
/* Save current newValue for next Check */
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putInt("old", newValue);
editor.commit();
do something....
}
newValue 的 key 是 "new" 还是 "newValue" ?你用密钥保存了它并用另一个检索
所以它找不到新值,所以它总是等于零
editor.putInt("newValue", 5);
int newValue = prefs1.getInt("new", 0);
因此您的 newValue 将等于 0,因为在 prefrences
中没有键 "new"
好吧,如果您想与活动分享偏好,那么您需要使用 getSharedPreferences(String, int) but you are using getSharedPreferences(int)
getSharedPreferences(int)
Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
像这样得到SharedPreference
对象
SharedPreferences prefs1 =getSharedPreferences ("app_prefs", Context.MODE_PRIVATE);
我从 activity1 获得了 NewValue 并按偏好存储并与来自 activity2 的 OldValue 进行比较:我的问题是它不存储 oldValue..
于 activity 1:
int i = 5;
SharedPreferences prefs1 = getPreferences(0);
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putInt("new", i);
editor.commit();
在 activity 2:
SharedPreferences prefs1 = getPreferences(0);
int oldValue = prefs1.getInt("old", 0);
int newValue = prefs1.getInt("new", 0);
/* Should Activity Check for Updates Now? */
if (oldValue < newValue) {
/* Save current newValue for next Check */
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putInt("old", newValue);
editor.commit();
do something....
}
newValue 的 key 是 "new" 还是 "newValue" ?你用密钥保存了它并用另一个检索
所以它找不到新值,所以它总是等于零
editor.putInt("newValue", 5);
int newValue = prefs1.getInt("new", 0);
因此您的 newValue 将等于 0,因为在 prefrences
中没有键 "new"好吧,如果您想与活动分享偏好,那么您需要使用 getSharedPreferences(String, int) but you are using getSharedPreferences(int)
getSharedPreferences(int)
Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
像这样得到SharedPreference
对象
SharedPreferences prefs1 =getSharedPreferences ("app_prefs", Context.MODE_PRIVATE);