How to Select File on android using Intent
Asked Answered
S

2

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

Smallminded answered 16/12, 2016 at 22:18 Comment(3)
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?Mitinger
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 .txtSmallminded
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 @MitingerSmallminded
R
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.

Raffarty answered 16/12, 2016 at 22:37 Comment(0)
P
11

Change the line :

chooseFile.setType("file/*");

to

chooseFile.setType("*/*");

This will help you choose any type of file.

Pascal answered 17/12, 2016 at 5:2 Comment(2)
@kaushik I want to fetch inly doc files [like .pdf .txt .doc .docs].Please helpShivers
Change to: chooseFile.setType( "/"); without the space between / to *Altair

© 2022 - 2024 — McMap. All rights reserved.