我正在android studio的片段中工作,在其中我试图通过单击按钮然后保存它然后再次检索它来从画廊中选择一个图像我再次启动应用程序。这是我从中选择图像的代码单击按钮并保存并检索它后的库。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_homepage, container, false);
iv = (ImageView) view.findViewById(R.id.profileImageView);
location=(TextView)view.findViewById(R.id.textView9);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openGallery();
}
});
retrieveImage();
return view;
}
private void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try
{
if (requestCode==RESULT_OK){
String path=getPathFromCameraData(data,getActivity());
Bitmap bmp=BitmapFactory.decodeFile(path);
iv.setImageBitmap(bmp);
storeImage(bmp);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String getPathFromCameraData(Intent data, Context context) {
Uri selectImage=data.getData();
String[] filepathColumn={MediaStore.Images.Media.DATA};
Cursor cursor=context.getContentResolver().query(selectImage, filepathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndx=cursor.getColumnIndex(filepathColumn[0]);
String piturepath=cursor.getString(columnIndx);
cursor.close();
return piturepath;
}
private boolean storeImage(Bitmap bitmap) throws IOException {
OutputStream outputStream=null ;
String directory=Environment.getExternalStorageDirectory().toString();
File file=new File(directory,"/friend");
if (file.exists())file.delete();
try{
outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
catch (Exception e){
e.printStackTrace();
}
return true;
}
public boolean retrieveImage(){
File f = new File(android.os.Environment.getDataDirectory() + "profile.jpg");
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
iv.setImageBitmap(bmp);
return true;
}