How to get any File Path ,Name ,Extension from onActivityResult?

Manoj Das picture Manoj Das · Mar 3, 2015 · Viewed 12k times · Source

My Codes are:

1.

File file = new File(Environment.getExternalStorageDirectory(),"myFolder");

            Log.d("path", file.toString());

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setDataAndType(Uri.fromFile(file), "*/*");
        startActivityForResult(intent,0);

2.

 @Override
    protected void onActivityResult(int requestCode, 
    int resultCode, Intent FileReturnedIntent) {
            // TODO Auto-generated method stub
            super.onActivityResult(requestCode, resultCode, FileReturnedIntent);

How to get the file path,name,extension? (suppose files are in doc,pdf,csv format)

Answer

Sohaib Aslam picture Sohaib Aslam · Jan 13, 2018

It return the file extention like pdf, doc .. etc

 public static String getMimeType(Context context, Uri uri) {
    String extension;

    if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
         final MimeTypeMap mime = MimeTypeMap.getSingleton();
        extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
    } else {
        extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());

    }

    return extension;
}

It returns you the real path where you get the file name. One friend use this way and it is really useful.

Get filename and path from URI from mediastore

public String getRealPathFromURI(Context context, Uri contentUri) {
  Cursor cursor = null;
  try { 
    String[] proj = { MediaStore.Images.Media.DATA };
    cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
  } finally {
    if (cursor != null) {
      cursor.close();
    }
  }
}

You get file name from this

public String getFileName(Uri uri) {
  String result = null;
  if (uri.getScheme().equals("content")) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    try {
      if (cursor != null && cursor.moveToFirst()) {
        result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
      }
    } finally {
      cursor.close();
    }
  }
  if (result == null) {
    result = uri.getPath();
    int cut = result.lastIndexOf('/');
    if (cut != -1) {
      result = result.substring(cut + 1);
    }
  }
  return result;
}