问题描述
我创建了一个Android的动态壁纸,我试图让用户选择自己的手机的图像,并将其应用为背景图像,但是当我启动的活动,开始有意挑选的图像,我共享preferences似乎并不正确保存。
下面是我开始时的用户presses的preference按钮活性的它获取设备上的图像的路径的onActivityResult(所有似乎工作)我onCreate方法,和。之后,我犯了preferences中的println打印出什么。
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
意图photoPickerIntent =新的意图(Intent.ACTION_PICK);
photoPickerIntent.setType(图像/ *);
startActivityForResult(photoPickerIntent,SELECT_PICTURE);
}
@覆盖
公共无效onActivityResult(INT申请code,INT结果code,意图数据){
super.onActivityResult(要求code,因此code,数据);
如果(结果code == RESULT_OK){
如果(要求code == SELECT_PICTURE){
乌里selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
。preferences = getApplicationContext()getShared preferences(preFERENCES_NAME,0);
。preferences.edit()putString(SETTINGS_BACKGROUND_IMAGE,OKOK);
preferences.edit()提交()。
的System.out.println(图像+ preferences.getString(SETTINGS_BACKGROUND_IMAGE,));
}
}
完();
}
在<一个href="http://developer.android.com/reference/android/content/Shared$p$pferences.html#edit%28%29">documentation:
由于这是一个新的编辑器的实例,你的code应该更多这样的:
preferences = getApplicationContext()getShared preferences(preFERENCES_NAME,0);
共享preferences.Editor编辑器= preferences.edit();
editor.putString(SETTINGS_BACKGROUND_IMAGE奥科克);
editor.commit();
I've created an Android live wallpaper and i'm trying to let a user choose an image from their phone and apply it as a background image, but when I launch the activity that start the intent to pick the images, my shared preferences don't seem to save properly.
Below is my onCreate method of the activity I start when the users presses the preference button, and the onActivityResult which gets the path of the image on the device (all that seems to work). The println after I commit the preferences prints out nothing.
@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();
}
From the documentation:
Since that's a new Editor instance, your code should be more like this:
preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SETTINGS_BACKGROUND_IMAGE, "okok");
editor.commit();
这篇关于Android的共享preferences不节能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!