我使用以下代码创建一组字符串,但每次调用 commit 时,它总是返回 false 并且从不保存,而是给出此错误:
Couldn't create directory for SharedPreferences file /data/user/0/com.identifier.my/shared_prefs/MyApp.xml
我每次都会创建一个新的哈希集。我从不修改返回的 stringSet,只是在另一个方法中迭代它。我尝试过使用
editor.apply()
并尝试在 while 循环中保存,直到 commit()
返回 true,但它永远不会这样做。
HashSet<String> params = new HashSet<>();
for (String strs : myExisitingStrings) {
params.add(strs);
}
SharedPreferences prefs =_context.getSharedPreferences("MyApp",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove("params"); //have tried with this line removed as well
editor.putStringSet("params",params);
boolean saved = editor.commit();
问题在于使用了错误的上下文。我的 apk 作为另一个应用程序中的插件运行,显然只能使用该应用程序的上下文,而不能使用插件。