I''m developing my first Android application and I'v run into a problem while trying to create a directory to save recorded video files.
I have a method in my main activity buttonOnClickRecord
that invokes an intent to use the android camera, I'm also creating a file during this method call and I'm calling the mkdirs()
method on it to create the directory to store the file.
I have also implemented <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in my Manifest.
public void buttonOnClickRecord(View v){
mediaFile =
new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/NewDirectory/myvideo.mp4");
mediaFile.mkdirs();
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
Uri videoUri = Uri.fromFile(mediaFile);
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
Toast.makeText(this, "Video saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Video recording cancelled.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Failed to record video",
Toast.LENGTH_LONG).show();
}
}
if I remove the /NewDirectory/
the video file is saved to the root of the sd card and I get a message to that affect from my onActivityResult
method.
But with the /NewDirectory/
added I get video saved to: content:://media/external/video/media/15625
the mediaFile.mkdirs();
is not creating the directory.
Where have I gone wrong?
You are trying to create a directory called myvideo.mp4
.
mediaFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/NewDirectory/myvideo.mp4");
mediaFile.mkdirs();
should be
File(Environment.getExternalStorageDirectory(), "NewDirectory");
mediaFile.mkdirs();
or better
mediaFile = new File(getExternalCacheDir(), "NewDirectory");
mediaFile.mkdirs();
Here you can find the documentation for getExternalCacheDir()
Be aware the from kitkat writing on the root of the sdcard is not allowed anymore.
Edit: the path to the file should be:
mediaFile = new File(getExternalCacheDir(), "NewDirectory");
File file = new File(mediaFile, "myvideo.mp4");
Uri videoUri = Uri.fromFile(file);