跨活动的SharedPreferences在子片段内返回null

时间:2019-02-27 11:40:01

标签: android sharedpreferences

嗨,我正在尝试在我的主要活动中保存一些信息SharedPreferences。但是,当我在其他活动的子片段中访问相同的信息时,它将返回null。

这就是我在做什么 主要活动

SharedPreferences sharedPreferences = getApplication().getSharedPreferences("UserDataInitially", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();   
 editor.putString("UserSearch",skill_set);
 editor.apply();
 editor.commit();

现在,当我在另一个活动的OnCreate方法中访问SharedPreferences时,它们将返回值

MainActivityUser

    String skill_set;
    SharedPreferences UserDataInitially = getApplication().getSharedPreferences("UserDataInitially", Context.MODE_PRIVATE);
    skill_set = UserDataInitially.getString("UserSearch","");

但在MainActivityUser的子片段中

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);

        SharedPreferences UserDataInitially= getContext().getSharedPreferences("UserDataInitially", Context.MODE_PRIVATE);
      skill_set = UserDataInitially.getString("UserSearch","");
      // Here skill_set is null
    }
}

1 个答案:

答案 0 :(得分:0)

这应该可行,因为您使用的是不同的上下文

 private void saveString(String key, String value) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.apply();
}

private String getString(String key, String defaultValue) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
    return sharedPreferences.getString(key, defaultValue);
}

参阅getDefaultSharedPreferences()