Android Studio - 无法将共享偏好保存到新 activity

Android Studio - The shared perference can't be saved on the new activity

正如问题提示的那样,无法将共享首选项保存到新 activity

Set<String> temp = getSharedPreferences("pref", MODE_PRIVATE).getStringSet("attempt", null);
temp.add("one item");
SharedPreferences editor = getSharedPreferences("pref", MODE_PRIVATE);
editor.edit().putStringSet("attempt", temp).commit();

此代码在主 activity 上运行完美。但是,当我尝试将此代码放在另一个 activity.

上时,它不起作用

编辑后的首选项可以在这段代码之后查看,甚至在新 activity 的 destroy(); 方法之后。但是,它正在刷新到保存的引用only with the added item in the main activity before.

我已经搜索了半小时,但我只找到关于“无法保存偏好”的问题,而不是“无法保存偏好 仅在新 activity"

我想知道我的代码是否有任何错误,我们将不胜感激。

为了使您的偏好在全球范围内可用,我建议执行 SharedPrefs.java class 来保存您的 SharedPreferences,如下所示:

public class SharedPrefs {

public static SharedPreferences prefs(Context context){
    return PreferenceManager.getDefaultSharedPreferences(context);
}

//Set your preference
public static void setMyPreference(Context context, String text) {
    prefs(context).edit().putString("MyPreference", text).apply();
}

//Get your preference
public static String getMyPreference(Context context) {
    return prefs(context).getString("MyPreference", "DefaultText");
}

并且使用以下代码,您可以将 Activity 中的数据作为 SharedPreference 保存到 SharedPrefs.java class:

//To save preferences in SharedPrefs
                String myString = "Hello world";
                SharedPrefs.setMyPreference(getContext(),myString);

或者从 SharedPrefs.java 获取到您的 Activity:

//To get preferences from SharedPrefs
                String getMyPreference = SharedPrefs.getCustomString(getContext());
                System.out.println(getCustomString);
                //Result = Hello world