Android 按钮不存在';t更新从SharedReference获取的数据

Android 按钮不存在';t更新从SharedReference获取的数据,android,button,sharedpreferences,android-sharedpreferences,Android,Button,Sharedpreferences,Android Sharedpreferences,我使用一些代码更新onActivityResult活动方法中的数据: //save state editorUserInfoSharedPreferences.putString("userType", productId); editorUserInfoSharedPreferences.putInt("paymentStatus", 1); editorUserIn

我使用一些代码更新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

我怎样才能解决这个问题?提前谢谢你

能否将代码粘贴到init:editorUserInfoSharedPreferences&userInfoSharedPreferences。有一件事我猜您正在使用两个不同的sharepreference对象。

在对EditorUserInfoSharedReferences执行提交后,在onActivityResult中初始化UserInfoSharedReferences


您正在获取旧值,因为您正在使用SharedReference的旧对象。

您应该使用commit或Apply。如果我同时使用这两个值,会出现问题吗?是的,其中一个是同步的,另一个是异步的。另外,如果您正在处理多个线程,并且正在处理main.thread,android建议使用apply()(同步),您可以使用commit.userinfosharedreferences=getsharedreferences(当前用户信息文件,模式为私有);EditorUserInfoSharedReferences=UserInfoSharedReferences.edit();