我有一些带有几个ImageView的活动。用户可以LongPress一个ImageView,他们可以选择从相机库中获取任何图像。我试图保存这些图像的图像路径,以便当用户关闭并再次打开应用程序时,图像仍将在imageView中。我不明白为什么这不起作用。
这是我的活动A,其中imageView是
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
im1.setImageURI(selectedImageUri);}}}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);};
@Override
protected void onPause() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1); // Open SharedPreferences with name AppSharedPref
Editor editor = sp.edit();
editor.putString("ImagePath", selectedImagePath); // Store selectedImagePath with key "ImagePath". This key will be then used to retrieve data.
editor.commit();
super.onPause();
}
protected void onResume1() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "");
super.onResume();
}
活动B获取凸轮库图片并发送回活动A
Button send = (Button) findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent();
setResult(RESULT_OK, intent);
Bundle bundle=new Bundle();
bundle.putInt("image",R.id.showImg);
intent.putExtras(bundle);
finish(); }
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}}}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
答案 0 :(得分:3)
请:
@Override
protected void onResume() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "");
Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagePath);
im1.setImageBitmap(myBitmap);
super.onResume();
}
而不是:
protected void onResume1() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "");
super.onResume();
}
因为您的活动扩展了Activity
类,它已声明并实现了此方法。在Activity
返回前台后调用此方法。你想要的是覆盖这个方法,以便它做你想做的。