0

I currently access a music file by creating an Intent

Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Audio "), MUSIC_CODE);

When the media selector appears, I can successfully choose a file and extract the corresponding URI

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data){
    if(requestCode == MUSIC_CODE){
        if(resultCode == RESULT_OK){
            //uri.getPath()
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}

Using the URI's path (e.g: /document/primary:music/filename.ext), how do I actually access the file to manipulate it or copy it? Thanks in advance, any links or tips are appreciated!

EDIT: I have tried getting a real path from the URI as follows but with no success (method continuously returns null):

public String getRealPathFromURI(Uri contentUri) {
    Cursor cursor = null;
    try { 
        String[] proj = { MediaStore.Audio.Media.DATA };
        cursor = getContentResolver().query(contentUri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
Daiwik Daarun
  • 3,804
  • 7
  • 33
  • 60

1 Answers1

0

In Android all the data related to the media files is persisted in the MediaStore database. So having an URI you can query the MediaStore database and retrieve the filepath. Please refer to this question:

Get filename and path from URI from mediastore

Community
  • 1
  • 1
Albert Sadowski
  • 642
  • 5
  • 8