Cannot save video to specific folder - android

I am trying to save video to specific folder like
Intent captureVideoIntent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
File videosFolder = new File(Environment.getExternalStorageDirectory(), "Videos");
if (!videosFolder.exists()) {
videosFolder.mkdirs(); // <----
}
String sfx = getNextName(ConstantData.RESPONSE_TYPE_VIDEO);
videoUri = Uri.fromFile(new File(videosFolder, sfx));
captureVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT,videoUri);
captureVideoIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(captureVideoIntent,1277);
videoUri is fine, folder Videos is created and on result when I try to read file like
InputStream inputStream = this.getContentResolver().openInputStream(videoUri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(8 * 8192);
....
I am getting exception FileNotFound, what is true, there is Videos folder but there is no saved video inside. Does anybody know what is problem and why I cannot save video to specific folder ? Video has extension .3gp and folder is always empty.

You can specify your new file name instead of the "sfx"
remove the below line and put "test.mp4" instead of the "sfx" variable, it will work
String sfx = getNextName(ConstantData.RESPONSE_TYPE_VIDEO);

Related

How to open my app documents directory with Android File Manager

I've been trying to figure out a way to open the Android File Manager directly in my app's Documents directory so the user can select a JSON file among several without requiring the user to go search for the file path /storage/emulated/0/Android/data/com.company.app/files/Documents/. So far, I can make the "go find it yourself" tactic work, but not the "take the user to the directory for them" approach. Here's what I've tried:
// this is the "go find it yourself" approach that I've used:
String filename = this.getResources().getString(R.string.ExportImportFileNameString);
File directory = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
Uri dirPathUri = Uri.fromFile(directory);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
Intent.createChooser(intent, "Open in...");
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, directory);
startActivityForResult(intent, IMPORT_REQUEST);
When my onActivityComplete handler is called for IMPORT_REQUEST I see the returned data looks like dat=content://com.lge.filemanager.FileProvider/storage/emulated/0/Android/data/com.company.app/files/Documents/SelectedFile.json flg=0x1 }
I've tried to invoke two different combinations of intent.setDataAndType instead of intent.setTypefollowing and that fails to let me select anything:
// This setDataAndType setup does not allow the user to open File Manager, nor navigate to the app Documents:
intent.setDataAndType(dirPath2, "application/json");
// This allows opening of File Manager but returns immediately without allowing the user to select a file, and returns a null data pointer:
intent.setDataAndType(dirPath2, "*/*");
Note that I've tried creating the intent object with ACTION_OPEN_DOCUMENT, ACTION_GET_CONTENT, and ACTION_VIEW with the similar result.
If I only have one file, I know I can have the app simply open a stream reader for a known file name as such:
File directory = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File importFile = new File(directory, filename);
try
{
fis = new FileInputStream (importFile);
InputStreamReader inputStreamReader =
new InputStreamReader(fis, StandardCharsets.UTF_8);
...
However, that doesn't allow me the flexibility that I desire to allow a user to select from multiple files. Can anyone illuminate what's going on here and how to correct the situation.
Based on Commonsware feedback, here's what I have for the solution to this question:
//--------------
// Get the documents location for this app
File directory = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File desiredFilePath = new File(directory.toString());
try{
// read all pathnames for files and directory
File[] allFilesInDirectory = desiredFilePath.listFiles();
// prepare array to place all path strings into
ArrayList<String> filesInDirectoryArray = new ArrayList<String>();
// retrieve each pathname file array
// but someone could simply use the "path" object instead
for(File path:allFilesInDirectory){
if (path != null){
// put all file paths into string array
filesInDirectoryArray.add(path.getPath());
// could discriminate based on file extension, if so desired
}
}
// send file path array for processing
ProcessDocuments(filesInDirectoryArray);
}catch(SecurityException e){
e.printStackTrace();
}

Storage in android studio

I am trying to pull multiple images from gallery and place in grid view , Unfortunately I am not able to do so, Can you help me with that. And also I made a folder in sd card and I m trying to store audio as well as photographs in the same folder. Can you help me with that as well?
I am using android 2.3.
So I have included this code inside the button click but on click of button it has created the folder but its not storing the file inside the folder. On click of the button every other thing is working, its opening the gallery and its calculating numpic. I am not sure why its not storing the file in CN Video folder.
public void onClick(View v) {
Intent pass_data = new Intent(MainRecord.this, OpenGallery.class);
pass_data.putExtra("numpic",numpic);
startActivity(pass_data);
// Saving Audio recorded file to directory
File f = new File(Environment.getExternalStorageDirectory() + "/CNvideo");
if(f.isDirectory()) {
//Write code for the folder exist condition
}else {
// create a File object for the parent directory
File CNvideoDirectory = new File("/sdcard/CNVideo/");
// have the object build the directory structure, if needed.
CNvideoDirectory.mkdirs();
// create a File object for the output file
String filename = getfilename();
File outputFile = new File(CNvideoDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
try {
FileOutputStream fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}};

From Uri to Path and back to Uri

I’m using some big pictures that are stored in External Memory. I decode them, resize them and set the small bitmaps to various imageviews.
I keep track of those large images by storing their Uri’s. When the app stops, I convert Uri to paths and save them as Strings is a SQLite base:.
File myFile = new File(provider.getImageUri().toString());
cv.put(DBHelper.DB_IMAGEPATH, myFile.getAbsolutePath());
At this point the path to the image looks like:
/content/media/.. and everything works ok.
When the app resumes I read the path from database and convert it to Uri:
File tempFile = new File(cursor.getString(imagePathColIndex);
mUri = (Uri.fromFile(mFile));
Now the path in new mUri looks like:
File:///content/... And there is a IONotFound exception.
You should try with
File tempFile = new File(cursor.getString(imagePathColIndex));
mUri = Uri.parse(tempFile.getAbsolutePath());
Testing with the following code
String path = "/content/media";
Uri uri = Uri.fromFile(new File(path));
Log.e(TAG, uri.toString()); //print file:///content/media
uri = Uri.parse(path);
Log.e(TAG, uri.toString()); //print /content/media
EDIT
To read the image can you try
BitmapFactory.decodeStream(new FileInputStream(Uri.parse(path)));

Can not play video from my internal application directory

It looks like I can not play videos stored in my internal application directory.
I have videos stored in /data/data/my.package.org/files/
And I'm trying to play a file from there using
String fpath = "/data/data/my.package.org/files/video.mpg"
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(fpath), "video/*");
But both Android default video player and some external videoplayer (MX player) say 'this video can not be played".
Whereas when I'm saving videos to SD card they are played fine.
Why is that?
Put your video in assets folder and use this code to play video with MediaPlayer
InputStream is = getResources().getAssets().open("video.mpg");
OR
Put your video in assets folder and...
String fpath = "/data/data/my.package.org/assets/video.mpg"
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(fpath), "video/*");
put your video in the res\raw folder. Then copy it out to the external directories where apps like video player can read them. Only your app can read /data/data/blah....
if its in res\raw, then
typeName = sourceSink.Types.video.toString();
for (sourceSink.VideoFiles video: sourceSink.VideoFiles.values() ){
resourceName = video.toString();
fileName = resourceName + ".mp4";
resource = getResources().getIdentifier(resourceName, "raw", "com.invodo.allshareplay");
createExternalStoragePublicFile(typeName,fileName,resource);
}
and then you can use this to copy it:
void createExternalStoragePublicFile(String fType, String fname, int res ) {
// Create a path where we will place our picture in the user's
// public pictures directory. Note that you should be careful about
// what you place here, since the user often manages these files. For
// pictures and other media owned by the application, consider
// Context.getExternalMediaDir().
File path = null;
if (((fType.equals(sourceSink.Types.photo.toString())) || (fType.equals(sourceSink.Types.file.toString())) ) ){
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
}
if (fType.equals(sourceSink.Types.music.toString())) {
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC);
}
if (fType.equals(sourceSink.Types.video.toString())) {
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES);
}
File file = new File(path, "/" + fname);
try {
// Make sure the Pictures directory exists.
path.mkdirs();
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(res);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
scanMedia(file);
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
then it's easy - just do the second half of the answer I provided and write them out. /data/data/ folder is never going to be viewed by anything other than your app.

Recorded Audio using Native Audio Recorder Issue

I am recording audio using Audio recorder (native app) of android.Using following code :
final Intent audioIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
String path = Environment.getExternalStorageDirectory()
.toString();
File AudioFolder = new File(path + "/MyFolder/",
"RecordedAudio");
File audioFile = new File(AudioFolder, "myaudio.mp4");
Uri audioFileUri = Uri.fromFile(audioFile);
audioIntent.putExtra(MediaStore.EXTRA_OUTPUT, audioFileUri);
startActivityForResult(audioIntent, 0);
Audio recording is working fine with me. After successful recording It has been stored default in sdcard. I am not able to store it with my particular folder "MyFolder" that is located in sdcard so It might be store in /sdcard/Myfolder/RecordedAudio/myaudio.mp4.
What is going wrong with my above code.?
Please help me with your suggestions.
Thanks

Categories

Resources