Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file size using URI in android

I am working on android video application where I am recording a Video using Camera Intent and taking a video from gallery. When recording video or after selecting video from gallery I want to know the size of my video which I took. I want to make a logic to show a user a toast message if selected Video size is greater then 5MB. I made the bottom logic which is not working and giving me 0 value where I tried to take the size from URI.

Thanks in advance.

My Logic which is not working

java.net.URI juri = new java.net.URI(uri.toString());
        File mediaFile = new File(juri.getPath());
        long fileSizeInBytes = mediaFile.length();
        long fileSizeInKB = fileSizeInBytes / 1024;
        long fileSizeInMB = fileSizeInKB / 1024;

        if (fileSizeInMB > 5) {
            Toast.makeText(this,"Video files lesser than 5MB are allowed",Toast.LENGTH_LONG).show();
            return;
        }

This is my code which I am using to get video from Gallery and to record video.

public void takeVideoFromCamera(){

        File mediaFile =new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/myvideo.mp4");

        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        Uri videoUri;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            videoUri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", mediaFile);
            videoUri = FileProvider.getUriForFile(this, "i.am.ce.by.ncy.provider", mediaFile);
        } else {
            videoUri  = Uri.fromFile(mediaFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 5491520L);//5*1048*1048=5MB
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT,45);
        startActivityForResult(intent, VIDEO_CAPTURE);
    }

    public void takeVideoFromGallery(){
        Intent intent = new Intent();
        intent.setType("video/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        long maxVideoSize = 5 * 1024 * 1024; // 10 MB
        intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, maxVideoSize);
        startActivityForResult(Intent.createChooser(intent,"Select Video"),REQUEST_TAKE_GALLERY_VIDEO);

    }

onActivityResult code

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == this.RESULT_OK) {

            switch (requestCode) {
                case VIDEO_CAPTURE:
                        if (resultCode == RESULT_OK) {
                            showVideoImage(data.getData());
// Here I want to know what is the size of my Video File
                        } 
                    break;
                case REQUEST_TAKE_GALLERY_VIDEO:
                    if (resultCode == RESULT_OK) {
                        showVideoGallery(data);
// Here I want to know what is the size of my Video File
                    } 
                    break;
          }
like image 300
Usman Khan Avatar asked Mar 21 '18 19:03

Usman Khan


People also ask

What is a URI in Android?

URI(Uniform resource identifier) as its name suggests is used to identify resource(whether it be a page of text, a video or sound clip, a still or animated image, or a program). The most common form of URI is the Web page address, which is a particular form or subset of URI called a Uniform Resource Locator (URL).

How do I check image size on android?

On android go to photos, select your photo and click the ... in the top right. Scroll to bottom of page to find image size.

How do you get MIME type corresponding to a content URI?

Retrieve a file's MIME type To get the data type of a shared file given its content URI, the client app calls ContentResolver. getType() . This method returns the file's MIME type. By default, a FileProvider determines the file's MIME type from its filename extension.


3 Answers

  1. Checks AssetFileDescriptor.length
  2. If not found, checks ParcelFileDescriptor.getStatSize implicitly inside AssetFileDescriptor.length
  3. If not found, check MediaStore/ContentResolver if URI has content:// scheme

Should work for file://, content:// schemes. Returns -1L if failed to find:

fun Uri.length(contentResolver: ContentResolver)
        : Long {

    val assetFileDescriptor = try {
        contentResolver.openAssetFileDescriptor(this, "r")
    } catch (e: FileNotFoundException) {
        null
    }
    // uses ParcelFileDescriptor#getStatSize underneath if failed
    val length = assetFileDescriptor?.use { it.length } ?: -1L
    if (length != -1L) {
        return length
    }

    // if "content://" uri scheme, try contentResolver table
    if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
        return contentResolver.query(this, arrayOf(OpenableColumns.SIZE), null, null, null)
                ?.use { cursor ->
                    // maybe shouldn't trust ContentResolver for size: https://stackoverflow.com/questions/48302972/content-resolver-returns-wrong-size
                    val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
                    if (sizeIndex == -1) {
                        return@use -1L
                    }
                    cursor.moveToFirst()
                    return try {
                        cursor.getLong(sizeIndex)
                    } catch (_: Throwable) {
                        -1L
                    }
                } ?: -1L
    } else {
        return -1L
    }
}
like image 121
Jemshit Iskenderov Avatar answered Oct 03 '22 17:10

Jemshit Iskenderov


AssetFileDescriptor fileDescriptor = getApplicationContext().getContentResolver().openAssetFileDescriptor(uri , "r");
long fileSize = fileDescriptor.getLength();
like image 39
Markus Rollmann Avatar answered Oct 03 '22 16:10

Markus Rollmann


java.net.URI juri = new java.net.URI(uri.toString());
File mediaFile = new File(juri.getPath());

A Uri is not a File.

showVideoImage(data.getData());

ACTION_VIDEO_CAPTURE does not return a Uri.

Moreover, you already know where the file is. You create a File object in takeVideoFromCamera() and use that for EXTRA_OUTPUT. Hold onto that File object (and also save it in the saved instance state Bundle), then use that for finding out the size of the resulting video.

like image 43
CommonsWare Avatar answered Oct 03 '22 18:10

CommonsWare