Android共享首选项未保存

标签 android preferences wallpaper preference

我创建了一个 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/

相关文章:

android - ActionBarSherlock 在 Android 2.3.3 上不显示任何内容

Android 3D按钮src填充

android - 全局控制处理程序

android - 如果这是主线程崩溃,如何从 UncaughtExceptionHandler 启动 Activity ?

java - 为什么我在这里得到一个 ClassCastException?

android - 设备中的wallpaperManager.getDesiredMinimumWidth()返回-1

android - 壁纸应该每天在Android手机上自动更换

java - 如何在 Swing 应用程序中设计用户首选项模块?

android - 使用首选项——我的 ListView 是空的(无法存储数据)

android - 如何让 .png 图片飞起来?