I am trying to upload a video to parse server using the camera intent to capture the videos.
the code is as follows. Now my problem is that the video is getting played in the videoView using the videoUri, BUT its not getting uploaded to the server. I am getting a FileNotFoundException saying that "there exists no such file or directory",
Example:-
I/info: content://media/external/video/media/57463 //this is the Log output for videoUri//
W/System.err: java.io.FileNotFoundException: /external/video/media/57463 (No such file or directory)
Can somebody please help with this issue??
public class VideoActivity extends AppCompatActivity {
static final int REQUEST_VIDEO_CAPTURE = 1;
Uri videoUri,vUri;
ParseUser currentUser;
VideoView videoView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
currentUser=ParseUser.getCurrentUser();
Button captureVideo = (Button) findViewById(R.id.captureVideo);
videoView=(VideoView) findViewById(R.id.videoView);
Button saveButton=(Button) findViewById(R.id.saveButton);
//save Button clicks handled here.
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(videoUri!=null){
Log.i("info", ""+videoUri);
byte[] bytes = convertVideoToBytes(videoUri);
//now lets try and add this uri file to the parse server in a parsefile.
ParseFile parseVideoFile = new ParseFile("video.mp4", bytes);
parseVideoFile.saveInBackground();
currentUser.put("video", parseVideoFile);
currentUser.saveInBackground();
}else{
Toast.makeText(VideoActivity.this,"No Video to save",Toast.LENGTH_LONG).show();
}
}
});
//capture video button click is handled here.
captureVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
});
}
//onActivityResult is shown here.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
videoUri = intent.getData();
videoView.setVideoURI(videoUri);
videoView.start();
}
}
//this is to convert the videoUri to byte[] arrays.
public static byte[] convertVideoToBytes( Uri videoUri) {
byte[] videoBytes = null;
File inputFile=new File(videoUri.getPath());
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(inputFile);
byte[] buf = new byte[(int)inputFile.length()];
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
videoBytes = baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return videoBytes;
}
}
here is my code..sorry for posting it as an answer but i didnt know how to post the code.
public class ViewActivity extends AppCompatActivity {
VideoView finalView;
Button button_play;
ParseUser currentUser;
String videoString;
Uri videoUri,contentUri, fileProvider;
File videoFile;
public final String APP_TAG = "MyCustomApp";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
finalView=(VideoView) findViewById(R.id.finalview);
button_play=(Button) findViewById(R.id.button_play);
// Create a File reference for future access
videoFile = getVideoFileUri();
fileProvider = FileProvider.getUriForFile(ViewActivity.this,
"com.codepath.fileprovider", videoFile);
currentUser= ParseUser.getCurrentUser();
ParseFile parseFile = (ParseFile)currentUser.get("videos");
parseFile.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
try {
videoUri=convertBytesToUri(data,fileProvider);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
button_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finalView.setVideoURI(videoUri);
finalView.start();
}
});
}
public Uri convertBytesToUri(byte[] data,Uri fileProvider) throws IOException {
OutputStream os=getContentResolver().openOutputStream(fileProvider);
os.write(data);
os.flush();
return fileProvider;
}
// Returns the File for a photo stored on disk given the fileName
public File getVideoFileUri() {
// Get safe storage directory for photos
// Use `getExternalFilesDir` on Context to access package-specific directories.
// This way, we don't need to request external read/write runtime permissions.
File mediaStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_MOVIES),
APP_TAG);
//Let's create a unique fileName.
String timeStamp=new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fileName=timeStamp+".mp4";
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
Log.d(APP_TAG, "failed to create directory");
}
// Return the file target for the photo based on filename
File file = new File(mediaStorageDir.getPath() + File.separator + fileName);
return file;
}
Related
I'm new in Android and I would create app that uses camera, store image taken from camera in device and show it in gallery? Anyone have any advice on how to do it? For now I have created the activity that allows you to take pictures but I don't know how to proceed to save and show the photos taken from the camera in the gallery. Please help me, I'm very desperate. Thanks in advance to everyone.
This is my code from android documentation:
public class CamActivity extends AppCompatActivity {
private ImageView imageView;
private Button photoButton;
private String currentPhotoPath;
private File photoFile = null;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_camera);
imageView = findViewById(R.id.taken_photo);
photoButton = findViewById(R.id.btnCaptureImage);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(checkPermissions()) {
dispatchTakePictureIntent();
galleryAddPic();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
} else {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
//File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File storageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Camera");
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
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
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Toast.makeText(CamActivity.this, "error" + ex.getMessage(), Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.myapp.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private boolean checkPermissions() {
//Check permission
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
//Permission Granted
return true;
} else {
//Permission not granted, ask for permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_IMAGE_CAPTURE);
return false;
}
}
}
allow camera and storage permission
public class CamActivity extends AppCompatActivity {
private ImageView imageView;
private Button photoButton;
private String currentPhotoPath;
private File photoFile = null;
private static final String TAG = "CamActivity";
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.taken_photo);
photoButton = findViewById(R.id.btnCaptureImage);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
captureImage();
}
});
}
#SuppressLint("QueryPermissionsNeeded")
private void captureImage() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(pictureIntent, 100);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
if (data != null && data.getExtras() != null) {
Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
saveImage(imageBitmap);
imageView.setImageBitmap(imageBitmap);
}
}
}
private void saveImage(Bitmap bitmap) {
String filename;
Date date = new Date(0);
#SuppressLint("SimpleDateFormat")
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
filename = sdf.format(date);
try {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream outputStream = null;
File file = new File(path, "/MyImages/"+filename + ".jpg");
File root = new File(Objects.requireNonNull(file.getParent()));
if (file.getParent() != null && !root.isDirectory()) {
root.mkdirs();
}
outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream);
outputStream.flush();
outputStream.close();
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (Exception e) {
Log.e(TAG, "saveImage: " + e);
e.printStackTrace();
}
}
}
The main theme of my app is, user has to select images from his device gallery, and those selected images are turned into a GIF. I'm converting those selected images into bitmap and I am using this GIFEncoder.java file to converted selected images into a GIF, and I have achieved it. when I check it in my folder, GIF was created but when I open the GIF is was not animating just a black screen was appeared.
Here is my MainActivity looks like:
public class MainActivity extends AppCompatActivity {
private static final int SELECT_PHOTO = 102;
private FileOutputStream outStream;
ArrayList<Bitmap> bitmaps = new ArrayList<>();
private Button generateImageGIF, selectImages;
String BASE_PATH = Environment.getExternalStorageDirectory().toString() + File.separator + "ImagesToGif";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File mydir = new File(BASE_PATH);
if (!mydir.exists()) {
mydir.mkdirs();
}
generateImageGIF = (Button) findViewById(R.id.generate_image_gif);
selectImages = (Button) findViewById(R.id.select_images);
selectImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
generateImageGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Toast.makeText(getApplicationContext(), "gif creation started", Toast.LENGTH_LONG).show();
outStream = new FileOutputStream(BASE_PATH + File.separator + getString(R.string.app_name) + ".gif");
outStream.write(generateGIF());
outStream.close();
Toast.makeText(getApplicationContext(), "gif creation ended", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null) {
Bitmap bitmap1 = BitmapFactory.decodeFile(String.valueOf(data.getData()));
bitmaps.add(bitmap1);
}
}
public byte[] generateGIF() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
}
this is my code it store captured picture form camera and save it on the SDcard but Now i want to enhance this code to taking pictures every 5 seconds If any body having an idea how to do this ,please share
public class MainActivity extends ActionBarActivity {
private final int requestCode = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int pictureCounter = 10;
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You should implement a runnable interface that uses threads. This way you could call the function on the OnClick method, then call Thread.sleep(timeinmilliseconds), then call the function inside the onClick method again, as many times as needed.
Here is an example of how to use threads:
http://www.wideskills.com/java-tutorial/java-threads-tutorial
I need to write text file in the smartphone internal memory, and then need to copy this .txt file to your computer via the USB cable and accessing his memory (This copy process will make manual, need to locate this file and understand which memory location will be recorded).
I am using the code below, which shows no errors when I run, but I do not know if this recording, and I do not know exactly what directory on your smartphone it should be.
This function is the button to call the function salvarInternalStorage
findViewById(R.id.distance_demo_button).setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Trilateration tri = new Trilateration(v.getContext());
try {
tri.salvarInternalStorage("Trying to Save This text Example");
} catch (IOException e) {
e.printStackTrace();
}
startListBeaconsActivity(DistanceBeaconActivity.class.getName());
}
});
This function is where you should write to the "File.txt" the text passed by parameter.
public void salvarInternalStorage(String texto) throws IOException{
// Use Activity method to create a file in the writeable directory
FileOutputStream fos = context.openFileOutput("FileTeste.txt", context.MODE_PRIVATE);
// Create buffered writer
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(String.valueOf(texto.getBytes()));
writer.close();
}
With SAF:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createFile("text/plain","Arquivo.txt");
}
private static final int WRITE_REQUEST_CODE = 43;
private void createFile(String mimeType, String fileName) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
// Filter to only show results that can be "opened", such as
// a file (as opposed to a list of contacts or timezones).
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Create a file with the requested MIME type.
intent.setType(mimeType);
intent.putExtra(Intent.EXTRA_TITLE, fileName);
startActivityForResult(intent, WRITE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==WRITE_REQUEST_CODE&&resultCode==RESULT_OK)
alterDocument(data.getData());
}
private void alterDocument(Uri uri) {
try {
ParcelFileDescriptor txt = getContentResolver().
openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream =
new FileOutputStream(txt.getFileDescriptor());
fileOutputStream.write(("Tentando Gravar Esse Texto Exemplo").getBytes());
fileOutputStream.close();
txt.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Or you can use the OPEN_DOCUMENT_TREE once to choose a directory and after that you have all permissions to save any file under that directory without ask the user. Something like this:
Uri sdCardUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case 1:
if (resultCode == Activity.RESULT_OK) {
sdCardUri = data.getData();
getContentResolver().takePersistableUriPermission(sdCardUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
createFile();
break;
}
}
private void createFile() {
DocumentFile sdCard=DocumentFile.fromTreeUri(this,sdCardUri);
DocumentFile createFile=sdCard.findFile("teste.txt");
if (createFile==null)
createFile=sdCard.createFile("text","teste.txt");
OutputStream outStream = null;
try {
outStream = getContentResolver().openOutputStream(createFile.getUri());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
String teste="Isto é um teste";
outStream.write(teste.getBytes());
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
How do i pass an uri from the onActivity result to another method in the same jave file.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == PICK_FROM_GALLERY) {
Uri mVideoURI = data.getData();
videoView.setVideoURI(mVideoURI);
videoView.start();
}
}
method savevideo:
public void savevideo() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SavedVideo/";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();;
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
File fileVideo = new File(dir.getAbsolutePath(), videoName);
try {
fileVideo.createNewFile();
success = true;
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
return true;
}
}
I would like like pass the mVideoURI to savevideo method and then save the video uri into gallery. Can someone help me with this. Any guidance/suggestion would be really helpful. Thank you.
EDITED: FULL CODING:
public class AndroidVideoPlayer extends Activity {
Button button;
VideoView videoView;
private static final int PICK_FROM_GALLERY = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_video_player);
button = (Button) findViewById(R.id.button);
videoView = (VideoView) findViewById(R.id.videoview);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == PICK_FROM_GALLERY) {
Uri mVideoURI = data.getData();
savevideo(mVideoURI);
videoView.setVideoURI(mVideoURI);
videoView.start();
}
}
public void savevideo(Uri mVideoURI) {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SavedVideo/";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();;
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
File fileVideo = new File(dir.getAbsolutePath(), videoName);
boolean success=false;
try {
fileVideo.createNewFile();
success = true;
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
}
}
As per my understanding from your question, you have to call a method after getting a result from another activity. so you might be called startActivitForResult(activityB) for getting the video Uri. so you will get a callback from the activityB, thus you can directly pass the video to the method saveVideo() since it is in the same Activity.
Example
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
if (requestCode == PICK_FROM_GALLERY) {
Uri mVideoURI = data.getData();
saveVideo(videoUri);
}
}
public void saveVideo(Uri videoUri){
// do operations with uri
}
or if you can't accept any arguments in saveVideo() method you can make uri as a member variable and use inside() method
use this code-
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == PICK_FROM_GALLERY) {
Uri mVideoURI = data.getData();
saveVideo(mVideoURI); // methode to save uri gets called here
videoView.setVideoURI(mVideoURI);
videoView.start();
}
}
method savevideo:
public void savevideo(Uri mVideoURI) {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SavedVideo/";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();;
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
File fileVideo = new File(dir.getAbsolutePath(), videoName);
try {
fileVideo.createNewFile();
success = true;
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
return true;
}
}
In your code, you are only creating new file on your destination path but not write the data of source file to destination file.
So you are getting 0KB file. Use the below code code for writing a file.
void savefile(URI sourceuri)
{
String sourceFilename= sourceuri.getPath();
String destinationFilename = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"abc.mp3";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while(bis.read(buf) != -1);
} catch (IOException e) {
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
}
}
}