【发布时间】:2017-07-21 04:52:37
【问题描述】:
我在Activity的onActivityResult方法中使用了一些代码来更新数据:
//save state
editorUserInfoSharedPreferences.putString("userType", productId);
editorUserInfoSharedPreferences.putInt("paymentStatus", 1);
editorUserInfoSharedPreferences.commit();
editorUserInfoSharedPreferences.apply();
int paymentStatus = userInfoSharedPreferences.getInt("paymentStatus", 0);
String userType = userInfoSharedPreferences.getString("userType", "");
Log.e(TAG, "paymentStatus 1700: "+ paymentStatus);
Log.e(TAG, "userType 1700: "+ userType);
日志中的数据是正确的。但在那之后,我点击了一个按钮并从 sharePreference 获取数据:
int paymentStatus = userInfoSharedPreferences.getInt("paymentStatus", 0);
String userType =
userInfoSharedPreferences.getString("userType", "");
Log.e(TAG, "paymentStatus 1532: "+ paymentStatus);
Log.e(TAG, "userType 1530: "+ userType);
日志中的数据是旧数据。 这是我的日志:
E/MAINACTIVITY: paymentStatus 1700: 1
E/MAINACTIVITY: userType 1700: monthly_0
....
E/MAINACTIVITY: paymentStatus 1532: 0
E/MAINACTIVITY: userType 1530: 0
我该如何解决这个问题?提前谢谢你!
【问题讨论】:
-
你应该使用 commit 或 apply
-
两个都用会有问题吗?
-
是的,其中一个是同步的,另一个是异步的。如果您正在处理多个线程,并且如果您正在处理 main.thread,那么 android 建议使用 apply()(同步),您可以使用 commit。
标签: android button sharedpreferences android-sharedpreferences