Cannot create a file using the Uri of `ACTION_GET_CONTENT` - android

I'm trying to select pdf file from the device and upload them to the server. ACTION_GET_CONTENT is used to select pdf from the device.
sel_book.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select PDF"), 1);
}
});
On activity result I get the Uri and save it as a String.
public void onActivityResult(int requestCode, int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Uri uri = result.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
path = myFile.getAbsolutePath();
}
}
}
It results the path as, /document/primary:Download/Aptitude_2016_17.pdf. I need to use this to create a new file. File selectedFile = new File(selectedFilePath);. But it doesn't create File. selectedFile.isFile() returns false. I have no idea why is it. Please help me to solve this. Thanks in advance.

ACTION_GET_CONTENT is used to select pdf from the device.
This allows the user to select a piece of content. It does not have to be a file.
On activity result I get the Uri and save it as a String.
That is not how you use a Uri.
It results the path as, /document/primary:Download/Aptitude_2016_17.pdf.
That is not a filesystem path. That is a part of a Uri that has a content scheme. You do not get a file from ACTION_GET_CONTENT. You get a Uri that points to a piece of content. That Uri could point to anything that the user and the other app choose:
A file that you can access, via a Uri with a file scheme
A file, but one that you cannot access (e.g., on internal storage of another app)
The contents of a BLOB column in the database
A piece of content that needs to be downloaded
And so on
Use ContentResovler and openInputStream() to get a stream on whatever the content is. Either use that directly (with whatever you are using to upload this content), or use that stream to make your own file with a copy of that content, so that you have a file that you can use.

Related

I Use Storage Access Framework to browse a file link f.cfg, when you select the file, the app need to load another file like f.dat automatically, how?

In Android Studio:
This app must use COMTRADE files. The COMTRADE files are *.cfg *.dat and *.rio files. For example, (user.cfg, user.dat and user.rio). The main file is *.cfg file, so the user must browse by SAF to find *.cfg files, when the user select this file, the app must load other files ( *.dat and *.rio) automatically.
I can not use <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/> for android level 30
So I have to use Storage Access Framework, By below code the user browse *.cfg files and select a file like user.cfg
if(SDK_INT >= Build.VERSION_CODES.R)
{
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
Act.startActivityForResult(intent, 111);
}
else
{...}
Then SAF return URI of that user.cfg file, and the app does not have any URI of other files to load.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 111)
{
if (resultCode == Activity.RESULT_OK)
{
if (data != null)
{
try
{
Uri uri = null;
uri = data.getData();
InputStreamReader inputStreamReader = new InputStreamReader(getContentResolver().openInputStream(uri));
BufferedReader br = new BufferedReader(inputStreamReader);
// I want URI of user.dat how?
InputStreamReader inputStreamReader1 = new InputStreamReader(getContentResolver().openInputStream(uri1));
BufferedReader br1 = new BufferedReader(inputStreamReader1);
....
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
}
Please help me how can I do this? Thanks.
Please help me how can I do this?
You cannot do this, at least by means of using ACTION_OPEN_DOCUMENT, unless you ask the user to open each of your three documents in turn. Just because the user selected a .cfg file does not mean that you have any rights to any other files, including those adjacent to it.
You could try using ACTION_OPEN_DOCUMENT_TREE and let the user choose the document tree that contains your desired files. From there, you can:
Use DocumentFile.fromTreeUri() to get a DocumentFile representing the tree
Call listFiles() on that DocumentFile to get the direct contents of that tree, in the form of a list of DocumentFile objects
Call getName() on each of those to get their display names, then see which names have your desired file extensions and matching base names (foo.cfg and foo.rio and foo.dat)
For those that you want to use, call getUri() on the DocumentFile to get a Uri to use with ContentResolver and openInputStream() to read in the content

Attaching files and uploading to server - Android Nougat

I am trying to upload files to server from my application. The user is allowed to attach the file from his internal storage. But some how the path I get from a Nougat phone is different from the standard /storage/emulated/0/... . in few phones I get external_files/... and in others I get root_files/storage/999/.... . In this case I am not getting the right path of the file. How do we handle this scenario?
My code :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = data.getData().getPath();
File sourceFile = new File(fileFields.get(i).getFileName());
FileInputStream fileInputStream = new FileInputStream(sourceFile);
}
}
A Uri is not a file. getPath() is meaningless unless the scheme of the Uri happens to be file. That will not be very common on newer Android devices. Instead, the scheme will be content, and getPath() will be useless to you.
Instead, for both file and content Uri values, use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. This approach works all the way back to Android 1.0.

Android How do I get text type file's name and path from local device?

search = (Button)findViewById(R.id.FindButton);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent,1);
}
});
I used ACTION_GET_CONTENT function to get file's name and local path.(setType is / but I want to get json file)
so this is my onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 1){
}
}
When I choose data and then what code do I put in there?
I used ACTION_GET_CONTENT function to get file's name and local path
ACTION_GET_CONTENT has nothing to do with files.
When I choose data and then what code do I put in there?
You are welcome to use a ContentResolver to query() for the OpenableColumns, which can give you a "display name". That is not necessarily a filename, because you are working with content, not files. See this sample app for getting the OpenableColumns using a CursorLoader.
However, you cannot get a "file path", as this is not a file. It is content. What you are asking is akin to asking how to get the file path for https://stackoverflow.com/questions/43878541/android-how-do-i-get-text-type-files-name-and-path-from-local-device.
You can use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. Decent JSON parsers (e.g., Gson) accept an InputStream and can parse the JSON from there.

Read .txt file from anywhere on the phone

In my app I have this code allowing the user to select a file :
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/plain");
startActivityForResult(intent,1);
The user can select the .txt file from anywhere in his phone, even from google drive. When the file selection is done I retrieve a Uri object corresponding to the file. The problem is I can't use this Uri to read the file because it is not valid. Here is my code :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
File file = new File(uri.toString());
try{
InputStream inputStream = new FileInputStream(file);
int content;
while ((content = inputStream.read()) != -1) {
Log.d("===>", String.valueOf((char) content));
}
}catch (Exception e){
Log.d("===>", e.toString());
}
}
}
}
I always get a fileNotFoundException. My question is, is there a way to read the selected file (without knowing in advance the location it will come from). And if not, is there a way to copy the selected file in a folder from which I would easily get it ?
The problem is I can't use this Uri to read the file because it is not valid.
That is because a Uri is not a file.
is there a way to read the selected file (without knowing in advance the location it will come from)
The user did not select a file. The user selected a piece of content.
To consume the content represented by the Uri, call openInputStream() on a ContentResolver, passing in the Uri. This gives you an InputStream that you can use to read in the content.

Can't save a photo to external storage using getFilesDir()

I'm trying to save a photo to external storage and display it in a ImageView, but I don't want other apps can access this photo. I try to create a new File with the method getFilesDir() as the directory argument when I want to create that file, but if I ask if I can write to it (to save the image), it return that I can't (see the code for more details).
Note that the app has the android.permission.WRITE_EXTERNAL_STORAGE permission.
public void takePhoto(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(getFilesDir(), "my_image.jpg");
// Check if I can write in this path (I always get that I can't)
if (file.canWrite()) {
Toast.makeText(this, "I can write!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "I CAN'T WRITE!", Toast.LENGTH_LONG).show();
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, IMAGE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_REQUEST_CODE) {
File file = new File(getFilesDir(), "my_image.jpg");
Bitmap bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
imageView.setImageBitmap(bitmap);
}
}
However, if I use the Environment.getExternalStorageDirectory() method, I'm able to save the photo.
I think I might be misunderstanding anything about how File works, but I don't know exactly what. I have no FC, the image just doesn't show in the ImageView.
If you save to an external storage everyone will see the image :
Here's External Storage!
Then when you receive the callback onActivityResult you will receive the URI from the image
Uri mUriFile = data.getData()
Then depending on the OS version you can get the file path
HereĀ“s a good post to get it Android Gallery on KitKat returns different Uri for Intent.ACTION_GET_CONTENT

Categories

Resources