3

I need to let the user select a file from their local storage for my application. Right now I'm using INTENT.ACTION_GET_CONTENT to let the user select the file, but it also gives the option of selecting URI from the cloud. After I get the URI file, I treat it as a local file and perform various things (including extracting the file extension). How can I let the user only pick local files?

else if(menuItem.getItemId() == R.id.action_import_from_file){
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.setType("*/*");
    startActivityForResult(Intent.createChooser(i, "Pick a file"), REQUEST_CODE_SELECT_FILE_FOR_IMPORT);
}
Komal12
  • 3,340
  • 4
  • 16
  • 25
ColonD
  • 954
  • 10
  • 28

3 Answers3

7

Please try using Intent.EXTRA_LOCAL_ONLY like
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
If the gallery app in your device supports it, only files in local storage will be displayed. If the gallery app does not support the above intent, you can show an error message to the user after checking the file length of the returned file path from gallery app.

Rahul
  • 202
  • 2
  • 8
2

Try this

 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
 intent.setType("image/*");
 intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
 startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);

try this use setType() method and specify what file type to choose by user

Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("application/pdf|application/x-excel|text/csv");
startActivityForResult(Intent.createChooser(i, "Pick a file"), REQUEST_CODE_SELECT_FILE_FOR_IMPORT);

you can also use array of MIME types like below code

Intent i = new Intent(Intent.ACTION_GET_CONTENT);
String[] types = {"application/x-excel/*", "application/csv/*",};
i.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
startActivityForResult(Intent.createChooser(i, "Pick a file"), REQUEST_CODE_SELECT_FILE_FOR_IMPORT);
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
  • does xlsx and csv files come under application? I'm importing datasets from excel files, csv files etc. – ColonD Sep 15 '17 at 08:50
1

Try this for only open csv and xlsx file it will select only csv and xlsx file

    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*");
    String[] mimetypes = {"application/vnd.openxmlformats- 
    officedocument.spreadsheetml.sheet", "text/csv"}; 
    intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
    startActivityForResult(intent, READ_REQUEST_CODE);
Deepak
  • 77
  • 7