Android 保存从库中拾取的图像以备将来使用
嘿,我已经找了一段时间了。下面的代码从android gallery中选取图像,并将其显示在imageView中。但问题是,每次关闭并重新启动应用程序时,都必须再次选择。我想知道如何编辑以下内容,以便在imageView中永久保存图像Android 保存从库中拾取的图像以备将来使用,android,gallery,android-gallery,Android,Gallery,Android Gallery,嘿,我已经找了一段时间了。下面的代码从android gallery中选取图像,并将其显示在imageView中。但问题是,每次关闭并重新启动应用程序时,都必须再次选择。我想知道如何编辑以下内容,以便在imageView中永久保存图像 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, re
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
用户选择的唯一东西是图片的路径。因此,如果您保存SharedReferences的路径,则每次启动应用程序时,您都可以使用现有代码,但只需更改获取路径的位置:
String picturePath = PreferenceManager.getDefaultSharedPreferences(this).getString("picturePath", "");
if(!picturePath.equals(""))
{
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
编辑:
这是可以在OnCreate中使用的完整方法:
String picturePath = PreferenceManager.getDefaultSharedPreferences(this).getString("picturePath", "");
if(!picturePath.equals(""))
{
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
else {
selectImage();
}
在“选择图像”中,使用当前代码启动拾取活动,然后在onActivityResult中使用以下命令:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("picturePath", picturePath).commit();
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
它似乎不起作用。选择的图像导致ImageView为空,我认为您误解了,第一次需要使用原始方法时,还需要保存共享首选项的路径,以便下次可以使用我的方法时,我尝试通过以下方式保存ShardReferences:。但该应用程序不断崩溃,称无法提供活动路径。还有别的办法可以保存路径吗?谢谢,行得通!。这是我以前使用的SharedReferences,这段代码在一个单独的项目中工作,但是当我将其添加到我自己的项目中时,图像不会应用于NPE。我以前在这里问过,但没有得到任何答案,也许你可以帮忙。