Я написал код, чтобы сделать снимок и сохранить его на внешнем хранилище. Если я запустил приложение и сделаю снимок, я получаю исключение File Not Found Exception.Android-файл не найден Исключение, сохраняя фотографию
Вот мой код:
public class CameraActivity extends BaseActivity {
//variables for navigation drawer
private String[] navMenuTitles;
private TypedArray navMenuIcons;
//request code
private static final int ACTIVITY_START_CAMERA_APP = 1777;
//ImageView for the thumbnail
private ImageView mPhotoCapturedImageView;
//File for folder
private File folder;
//variable for timestamp
String timeStamp = "";
//Requestcode for external Storage Permission
final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 42;
//FloatAction Button to save the picture
private FloatingActionButton save;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
/*
* Initialize nav draw items
*/
//load title from String.xml
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
//load icons from String.xml
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
//set title and icons
set(navMenuTitles, navMenuIcons);
//initialize ImageView
mPhotoCapturedImageView = (ImageView) findViewById(R.id.imgViewThumbNail);
//creat new intent for the camera app
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//creat and set a timestamp
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//check if permission granted
if (ActivityCompat.checkSelfPermission(CameraActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
if (folder == null) {
createFolder();
}
} else {
ActivityCompat.requestPermissions(CameraActivity.this, new String[]
{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
}
/*
//create a file with timestamp as title and save it in the folder
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + "MyIdea" + File.separator + "IdeaGallery" + File.separator +
"IMG_" + timeStamp + ".jpg"); */
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(folder));
//start the camera app
startActivityForResult(intent, ACTIVITY_START_CAMERA_APP);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours:
if (requestCode == ACTIVITY_START_CAMERA_APP)
{
File foto = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Pictures/", "MyIdea/IdeaGalery/" +
"IMG_" + timeStamp + ".jpg");
Bitmap bitmap = decodeSampledBitmapFromFile(foto.getPath(), 1000, 700);
mPhotoCapturedImageView.setImageBitmap(bitmap);
MediaScannerConnection.scanFile(CameraActivity.this, new String[]{foto.getPath()}, new String[]{"image/jpeg"}, null);
//Get our saved file into a bitmap object:
//File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +File.separator + "MyIdea" + File.separator + "IdeaGallery" + File.separator + "IMG_" + timeStamp + ".jpg");
//Bitmap photoCapturedBitmap = BitmapFactory.decodeFile(mImageFileLocation);
}
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height/(float)reqHeight);
}
int expectedWidth = width/inSampleSize;
if (expectedWidth > reqWidth)
{
inSampleSize = Math.round((float)width/(float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
private void createFolder() {
folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/", "MyIdea/IdeaGalery/" +
"IMG_" + timeStamp + ".jpg");
folder.mkdir();
Toast.makeText(getApplicationContext(), "Folder created", Toast.LENGTH_LONG).show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION && grantResults.length > 0 &&
grantResults [0] == PackageManager.PERMISSION_GRANTED) {
createFolder();
}
}
}
разрешения на Android Manifest были установлены ALS
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Может кто-нибудь помочь, пожалуйста, помогите мне найти ошибку?
Почему вы используете запятую между путь к файлу? – Chordin4tion
Хороший вопрос: D. Я установил ее в 'папку = новый файл (Environment.getExternalStorageDirectory() getAbsolutePath() + "/ Фотографии/MyIdea/IdeaGalery /" + "IMG_" + TIMESTAMP + ".jpg".);' Но Файл не найден. Исключение все еще существует. – dudi
Пожалуйста, опубликуйте полное сообщение .. И сообщите, какое заявление вызывает это сообщение. – greenapps