Getting a files extension from Filepicker-Intent

1.2k views Asked by At

This is part of my activity class. By calling the below Intent i open a file-picker intent to select an image or video. This works so far.

public class Activity extends AppCompatActivity {

    EditText et;
    private static final int PICKFILE_RESULT_CODE = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // EditText to show filepath after intent
        et = (EditText)findViewById(R.id.et);

        // Start intent to pick a file
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*|video/*");
        startActivityForResult(intent,PICKFILE_RESULT_CODE);
    }

Here I retrieve the file's path:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode)
        {
            case PICKFILE_RESULT_CODE:
                if(resultCode==RESULT_OK){

                    // Get path of selected file and set it to editText
                    String filePath = data.getData().getPath();
                    et_upload.setText(filePath);
                }
                break;
        }
    }
}

The result looks like,

"/path/to/file/fileName".

but I want to include the files extension:

"/path/to/file/fileName.png"

Anything I missed?

Thank you in advance for any help. :)

1

There are 1 answers

0
CommonsWare On

This works so far.

setType() does not support the | operator.

Anything I missed?

First, the path alone is meaningless. ACTION_GET_CONTENT will typically return a content:// Uri, and the path is only meaningful to the ContentProvider. For example, this is not a path to a file on a filesystem.

Second, that Uri does not have to include a file extension.

If you want to know the MIME type of the content backed by that Uri, use a ContentResolver and its getType() method. If you want to convert that MIME type into a file extension, use MimeTypeMap.