我希望你能帮助我。这是我第一次在这里写一个问题。
我想从图库中选择一个图像并将其显示在ImageView中。关闭该活动并重新打开后,我想显示我们之前选择的图像。选择图像 - >在ImageView中显示图像 - >保存图像选择 - >关闭活动 - >打开活动 - >显示图像选择。希望我足够清楚。
从图库中选择图像并将其加载到ImageView中的第一部分正在工作,给我带来问题的是目前我正在尝试在SharedPreferences / Preferences中保存所选图像或其路径,但在再次打开活动时它不显示。使用SharedPreferences / Preferences保存和加载似乎有效,但它不会显示图片。
我试过它:Path,EncodedPath等等但似乎什么都没有用。我究竟做错了什么 ?
要打开画廊:
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
gallery.setType("image/*");
startActivityForResult(gallery, RESULT_LOAD_IMAGE);
用于保存图像:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
Uri imageUri = data.getData();
imageView.setImageURI(imageUri);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("imageURI", imageUri.getEncodedPath());
editor.commit();
}
}
用于加载所选图像:
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
String imageUriString = settings.getString("imageURI", "");
Uri imageUri = Uri.parse(imageUriString);
Picasso.with(this)
.load(imageUriString)
//.load(testarrraylogo.get(position))
.placeholder(R.drawable.otto)
.error(R.drawable.hochbahn)
// To fit image into imageView
.fit()
// To prevent fade animation
.noFade()
.into(imageView);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("imageURI", imageUri.getEncodedPath());
editor.commit();
成
SharedPreferences.Editor editor = getSharedPreferences("preference",
MODE_PRIVATE).edit();
editor.putString("imageURI", "uriPathstring"); //Your URI PATH STRING
editor.apply();
并检索像这样
SharedPreferences prefs = getSharedPreferences("preference, MODE_PRIVATE);
String imageUri = prefs.getString("imageURI", null);
在毕加索加载图像
Picasso.with(context).load(new File(imageuri)).into(imageView);
第一次检索图像时你没有使用Picasso加载图像,你可以用这个imageView.setImageURI(imageUri);
替换这个Picasso.with(YourActivity.this).load(imageData).into(imageView)
然后将Uri保存到SharedPreferences,您可以执行类似这样的editor.putString("imageURI", imageUri.toString);
,然后使用
try {
imageUri = URI.create(myPrefs.getString("imageURI", "defaultString"));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}