我有一个使用相机拍摄图像的应用程序。
String[] galleryPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(this, galleryPermissions)){
//Camera
if (index == 0) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Toast.makeText(getApplicationContext(),ex.getMessage(),Toast.LENGTH_LONG).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = null;
// N is for Nougat Api 24 Android 7
if (Build.VERSION_CODES.N <= android.os.Build.VERSION.SDK_INT) {
// FileProvider required for Android 7. Sending a file URI throws exception.
photoURI = FileProvider.getUriForFile(this,
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
Log.v("highbuild",photoURI.toString());
} else {
// For older devices:
// Samsung Galaxy Tab 7" 2 (Samsung GT-P3113 Android 4.2.2, API 17)
// Samsung S3
photoURI = Uri.fromFile(photoFile);
Log.v("lowbuild",photoURI.toString());
}
imageuriduplicate = photoURI;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, 0);
}
else{
Log.v("file", "photo file is null");
Toast.makeText(getApplicationContext(),"Photo file is null", Toast.LENGTH_LONG).show();
}
}
}
//Gallery
else if (index == 1) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
pickPhoto.setType("image/*");
startActivityForResult(pickPhoto, 1);//one can be replaced with any action code
}
}
else {
EasyPermissions.requestPermissions(this, "Access for storage",
101, galleryPermissions);
}
我的创建文件图像方法是这样的
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "AndroidUpload" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if(!storageDir.exists()){
boolean s = new File(storageDir.getPath()).mkdirs();
if(!s){
Log.v("not", "not created");
}
else{
Log.v("cr","directory created");
}
}
else{
Log.v("directory", "directory exists");
}
File image = File.createTempFile(
imageFileName, /* prefix */
".png", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
然后我将路径保存到arraylist并访问它。
但是当我尝试访问这样的文件时
Uri imageuri = Uri.parse(receipts.get(i).imageURI);
File file = new File(imageuri.getPath());
if(file.exists()){
Log.v("exists","file exists");
}
else{
Log.v("no","file doesnt exist");
}
我得到的文件不存在错误。
我已经提供了所有必要的权限,但我仍然遇到此错误。怎么解决这个问题?
答案 0 :(得分:1)
确保storageDir存在。如果没有使用
创建目录new File(path_to_dir).mkdirs();