gpt4 book ai didi

Android共享首选项未保存

转载 作者:IT王子 更新时间:2023-10-29 00:10:36 26 4
gpt4 key购买 nike

我创建了一个 Android 动态壁纸,我试图让用户从他们的手机中选择一张图片并将其应用为背景图片,但是当我启动启动 Intent 选择图片的 Activity 时,我的共享首选项似乎无法正确保存。

下面是我在用户按下首选项按钮时启动的 Activity 的 onCreate 方法,以及获取设备上图像路径的 onActivityResult(所有这些似乎都有效)。我提交首选项后的 println 什么也没有打印出来。

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PICTURE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);

preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, 0);
preferences.edit().putString(SETTINGS_BACKGROUND_IMAGE, "okok");
preferences.edit().commit();

System.out.println("Image" + preferences.getString(SETTINGS_BACKGROUND_IMAGE, ""));
}
}

finish();
}

最佳答案

来自 documentation :

Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.

因为这是一个新的编辑器实例,你的代码应该更像这样:

preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SETTINGS_BACKGROUND_IMAGE, "okok");
editor.apply();

关于Android共享首选项未保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9677719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com