Search code examples
androidonactivityresult

Pick file via Intent then Delete onActivityResult


I would like to open a directory, after which I should able to pick a file then delete it. This is my code to open the directory:

public void openDirectory() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + "/drugdiy/doc");
        intent.setDataAndType(uri, "*/*");
        startActivityForResult(Intent.createChooser(intent, "Open folder"), 0);
    }

I am stuck with how to pass the uri to onActivityResult so that I can delete it?

    public void onActivityResult(int requestCode, int resultCode, Intent data){
        switch (requestCode) {
            case 0: {
                Uri uri = 
                File file = new File(uri.getPath());
                file.delete();
            }
        }
    }

Solution

  • First, if you read the documentation for ACTION_GET_CONTENT, you will see:

    Input: getType() is the desired MIME type to retrieve. Note that no URI is supplied in the intent, as there are no constraints on where the returned data originally comes from.

    (emphasis added)

    So, your first code snippet will work on few devices.

    Second, ACTION_GET_CONTENT does not have to return to you a file, let alone one that you can delete.

    There are many file-picker libraries available for Android. Use one. They should give you a File back, and you can then call delete() on the File.