0
我有一个允许用户拍摄图片的活动,onActivityResult()
将在缓存dir中创建一个临时文件以存储它,然后将其上传到服务器。即使file.delete()返回true,文件也不会被删除
我这是怎么开始的意图:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CODE_CAMERA);
这里是内部onActivityResult代码:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CODE_CAMERA) {
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
File photoFile = new File(getActivity().getCacheDir(), "userprofilepic_temp.jpg");
boolean b = false;
if(photoFile.isFile()){
b = photoFile.delete();
}
b = photoFile.createNewFile(); //saves the file in the cache dir, TODO delete this file after account creation
userPhotoFilePath = photoFile.getAbsolutePath();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
FileOutputStream fos = new FileOutputStream(photoFile);
fos.write(bytes.toByteArray());
fos.close();
displayUserPhoto(photoFile);
} catch (IOException e) {
e.printStackTrace();
}
}
else if (requestCode == REQUEST_CODE_PHOTO_LIBRARY) {
}
}
}
而且displayUserPhoto仅仅是一个简单的滑行电话:
@Override
public void displayUserPhoto(File photoFile) {
Glide.with(this)
.load(photoFile)
.into(userPhotoView);
}
因为我想覆盖以前的图片,如果用户决定重新拍照,我检查photoFile是否是一个文件。如果是,我删除它。然后创建一个新文件。
问题是它总是返回相同的初始图片。即使我拨打.delete()
,该文件也不会被删除。
由于我正在使用应用程序的缓存目录,我不需要写入权限,但只是incase我试图包括,但它仍然无法正常工作。
编辑:添加了完整的流程如下
您是否尝试过通过这个在调试器步进,以后'删除()'打破,并观察是否再创建该文件实际上是删除和写入新一?如果是这样,那么您所看到的行为可能会由于将相同的数据重新写入新文件而导致。 –
“即使我调用.delete(),该文件也不会被删除。” - 即使文件未被删除,您也覆盖其内容。因此,你的问题在别处,也许在你的'displayUserPhoto()'实现中。此外,请删除'ByteArrayOutputStream',因为这是一个可怕的内存浪费,因为您只是转过身来使用'FileOutputStream'写数据。将'FileOutputStream'传递给'compress()'。 – CommonsWare
@CommonsWare我添加了完整的流程。我不知道它会在哪里搞乱。流程看起来很基本。 – Sree