14

I use this code to use Intent to select any type of file and get it's path in my application

    //this when button click
public void onBrowse(View view) {
    Intent chooseFile;
    Intent intent;
    chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
    chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
    chooseFile.setType("file/*");
    intent = Intent.createChooser(chooseFile, "Choose a file");
    startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) return;
    String path     = "";
    if(requestCode == ACTIVITY_CHOOSE_FILE)
    {
        Uri uri = data.getData();
        String FilePath = getRealPathFromURI(uri); // should the path be here in this string
        System.out.print("Path  = " + FilePath);
    }
}

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

the problem when the file browser open i can't select a file it seems like it's not enable when i pressed on a file nothing happend so what is the wrong with this code
i upload a screenshot from my android mobile
image
Thanks in advance

user7179690
  • 1,051
  • 3
  • 17
  • 40
  • 1
    `file/*` isn't a valid mime type. What kinds of files do you accept? Why are you trying to get a path from a file? What do you want to do with the file you accept? – ianhanniballake Dec 16 '16 at 22:25
  • I have a project of data structure that I want to get a file that has hundreds of queries the type of a file is .txt – user7179690 Dec 16 '16 at 22:28
  • I upload an image from my android app i can't select any kind of file so what should i do to make it work i try this too file/*.txt but not work @ianhanniballake – user7179690 Dec 16 '16 at 22:35

2 Answers2

12

the type of a file is .txt

Then use text/plain as a MIME type. As Ian Lake noted in a comment, file/* is not a valid MIME type.

Beyond that, delete getRealPathFromURI() (which will not work). There is no path, beyond the Uri itself. You can read in the contents identified by this Uri by calling openInputStream() on a ContentResolver, and you can get a ContentResolver by calling getContentResolver() on your Activity.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
11

Change the line :

chooseFile.setType("file/*");

to

chooseFile.setType("*/*");

This will help you choose any type of file.

Community
  • 1
  • 1
Jessy Swan
  • 121
  • 4