简体   繁体   中英

ACTION_GET_CONTENT gives wrong path

I'm using ACTION_GET_CONTENT so that the user can select text files that the rest of my code can read and deal with.

Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("text/*");
startActivityForResult(Intent.createChooser(intent, "select data"), SELECT_DATA);

Above is my code so that the user can browse which works fine.

Uri DataUri = data.getData();
File FileUri = new File(DataUri.getPath());

If I convert DataUri or FileUri to a string after using getPath or getAbsolutePath, I get a completely wrong path.

The path should be /storage/emulated/0/Documents/myFile but it gives me /document/primary:Documents/myFile. I have no idea what this "primary:Documents" thing is.

The data from the intent itself already has the wrong path, any suggestions?

I'm using ACTION_GET_CONTENT so that the user can select text files

No, you are using ACTION_GET_CONTENT so that the user can select some content that has a MIME type of text/* . Where that content comes from is largely up to the user. It may or may not be a file on the filesystem, and if it is, is may or may not be a file that you could access yourself directly (eg, internal storage of the Dropbox app, files on removable storage on Android 4.4+ devices).

The path should be /storage/emulated/0/Documents/myFile

No, it should not.

but it gives me /document/primary:Documents/myFile

What you get will vary by whatever activity handles the ACTION_GET_CONTENT request. What that activity is will depend on what the user has installed that supports ACTION_GET_CONTENT and what the user chooses out of that list of installed stuff.

Usually, you will get a content Uri (ie, getScheme() on Uri will return content ), as the Uri will point to data being served by a ContentProvider .

The data from the intent itself already has the wrong path

It has the correct path. It is simply not a path on the filesystem.

any suggestions?

Use a ContentResolver and openInputStream() to get an InputStream for the content represented by the content Uri .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM