2

I do this to get and show the path of an image, but I would like to know how I could do the same with a text file.

val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
intent.type = "image/*"
startActivityForResult(intent, SELECT_IMAGE)
SonhnLab
  • 321
  • 1
  • 11
Adrian Pang
  • 15
  • 1
  • 4

1 Answers1

1

I think you could try

 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
 intent.setType("text/*");
 startActivityForResult(intent,PICKFILE_RESULT_CODE);

following to get the uri

 @Override
 protected void onActivityResult(..., Intent data) {
 //do your validation

 switch (requestCode) {
        case PICKFILE_RESULT_CODE:
        ...
        Uri uri = data.getData();
        Log.d(TAG, "File Uri: " + uri.toString());
        try {
              Log.d(TAG, "File path: " + getPath(this, uri));
          } catch (URISyntaxException e) {
              e.printStackTrace();
          }
        //do your work
        ...
        break;
    }
}

Add in utils

public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
    String[] projection = {"_data"};
    Cursor cursor = null;

    try {
        cursor = context.getContentResolver().query(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow("_data");
        if (cursor.moveToFirst()) {
            return cursor.getString(column_index);
        }
    } catch (Exception e) {
        // Eat it
    }
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
    return uri.getPath();
}

return null;
}
Sree...
  • 333
  • 2
  • 7