作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我创建了一个 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/
我是一名优秀的程序员,十分优秀!